Jump to content

  • Log In with Google      Sign In   
  • Create Account


#Actuallwm

Posted 28 February 2013 - 10:28 AM

As far as I can see using MonoDevelop, the IL instantiates a new object. The question is whether the JIT optimizes this.

 

"newing" a struct should not instantiate a new object.

 

var x = new MyClass(1.5f);

 

will turn into

ldc.r4 1.5 // push 1.5f onto the evaluation stack
newobj instance void MyClass::.ctor(float32) // allocate object, call .ctor on it with value from stack and push reference to new object
stloc.0 // store reference in x (x is first local variable in this case)

 

whereas

var x = new MyStruct(1.5f);

 

will turn into

ldloca.s x // push reference to x
ldc.r4 1.5 // push 1.5f
call instance void MyStruct::.ctor(float32)

The struct's constructor is just a "normal" method. This call will almost certainly be inlined. Unless you start boxing the value, use it in a lambda expression or things like that, there should be no need for any heap allocations.


#2lwm

Posted 28 February 2013 - 10:26 AM

As far as I can see using MonoDevelop, the IL instantiates a new object. The question is whether the JIT optimizes this.

 

"newing" a struct should not instantiate a new object.

 

var x = new MyClass(1.5f);

 

will turn into

ldc.r4 1.5 // push 1.5f onto the evaluation stack
newobj instance void MyClass::.ctor(float32) // pop the 1.5f, allocate object and push reference to object
stloc.0 // store reference in x (x is first local variable in this case)

 

whereas

var x = new MyStruct(1.5f);

 

will turn into

ldloca.s x // push reference to x
ldc.r4 1.5 // push 1.5f
call instance void MyStruct::.ctor(float32)

The struct's constructor is just a "normal" method. This call will almost certainly be inlined. Unless you start boxing the value, use it in a lambda expression or things like that, there should be no need for any heap allocations.


#1lwm

Posted 28 February 2013 - 10:22 AM

As far as I can see using MonoDevelop, the IL instantiates a new object. The question is whether the JIT optimizes this.

 

"newing" a struct should not instantiate a new object.

 

var x = new MyClass(1.5f);

 

will turn into

ldc.r4 1.5
newobj instance void MyClass::.ctor(float32)
stloc.0 // x is first local variable in this case 

 

whereas

var x = new MyStruct(1.5f);

 

will turn into

ldloca.s x
ldc.r4 1.5
call instance void MyStruct::.ctor(float32)

The struct's constructor is just a "normal" method. This call will almost certainly be inlined. Unless you start boxing the value, use it in a lambda expression or things like that, there should be no need for any heap allocations.


PARTNERS