[Programming c#] Use structs instead classes in a loops

Structs in c# enable the development of efficient pieces of code where the managed dynamic memory is not required. Structs in .net are value types. That means that they can be allocated in the stack efficiently instead of the heap. Thanks to this you can have a chunk of data that acts like an object (it has fields and methods) but avoiding the call of the memory management system (garabage collection, that may even call to the operative system to reserve more memory).

For instance, let the simple struct A:

		struct A
		{
			public int val;

			public A(int v)
			{
				this.v=val;
			}

			public void foo()
			{
				Console.WriteLn(val);
			}
		}

The following sample shows the function “bar” that uses the struct “A” intensively in a loop (a typical scenario where efficiency may be very relevant).


         void bar()
         {
             for(int i=0;i<1000;i++)
             {
                 A a;
                 a.val=i;
                 a.foo();
             }
         }

The use of A as an struct instead a class has three main benefits:

  1.  First a construction function call is avoided. Avoiding function calls in loops may boost the process. For instance, function calls typically decreases the performance of the processor dynamic scheduling or even because of static optimization techniques like performed by the compiler or JITTER (such as loop unrolling).
  2. It is not required to call the dynamic memory management system. That means that the memory management system in .net does not need to create a new node for the object. Moreover any call to the operative system to reserve more memory for the process is totally avoided.
  3.  No garbage collection is required at all since the struct is not in the memory heap. The “deallocation of the object” is automatically done (with no processing cost) when the current function returns back to the calling function (change of stack frame).

However, sometimes it is required to make some kind of initialization process for the struct. Because of this c# structs can be initialization using a parametric constructor. Structs constructors are invoked using the “new” keyword. That may be confusing because the “new” keyword has been historically used in other languages (such as c++) as a method to reserve dynamic memory. If the constructor is called, the benefit 1 is lost, however the benefits 2 and 3 are still maintained.


         void bar()
         {
             for(int i=0;i<1000;i++)
             {
                 A a = new A(4);
                 a.foo();
             }
         }

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: