views:

210

answers:

5

Is there any time in which a reference type is more efficient than a value type ? Why ? Can you give an example ?

+9  A: 

Any time you're going to pass it around between lots of objects.

Each call into a method with a value type, or each time it's assigned to another location, requires a complete copy of the value type's members. If you have quite a few members, this can lead to a huge loss in performance.

For example, say you have an object with 20 int values:

public class MyClass { int a; int b; int c; ... }
public class MyStruct { int a; int b; int c; ... }

If we do this:

MyClass class = new MyClass();
MyClass struct = new MyStruct();

this.CallSomeMethod(class); // Just copies one IntPtr reference!
this.CallSomeMethod(struct); // Needs to copy a large amount of data to run - 20x the other on x86, 10x on x64, since it's 20 Int32 values!
Reed Copsey
+4  A: 

The question is too broad to have a definite answer. An example case can be where you have a 10k object and are passing it to a recursive function. If you use a value type, every time you call a method, you'll be copying the whole thing.

Mehrdad Afshari
A: 

Value Type member can be accessed without an additional level of indirection. In general reference types are a good staring point. You should profile your application and if you get serious performance problems by referencing members you could try to use value types if it is applicable by design.

For very small structs you could prefer value types without profiling. Especially if your strct contains only four byte values or something like this. On 64 Bit plattforms every reference (indirection) costs 8 Byte of memory. Keep in mind that the upcoming x64 Windows versions can store 8 Bytes in a CPU register. If your struct is as small as 8 Bytes it can be hold into a register.

As already posted keep in mind that value types must be copied completely on a call by value. If your structs are much bigger than 8 Bytes this can cause a huge performance impact.

Thomas Maierhofer
A: 

If by efficient we mean less instructions to the CPU then:

  1. Value types have a default constructor initializing the default value, while reference types defaults to a null reference.

  2. Changing the value of one value type does not affect another value type while changing the value of a reference type might change the value of other reference types.

AlejandroR
A: 

I try to think more about semantics rather than performance unless I profile there really is a problem there. So if I want something that behaves like a value and has value semantics then I use a struct, otherwise I use a class.

I believe in most code this works fine, as if your object is complex enough for performance to be a problem you probably don't want value semantics anyway.

KeeperOfTheSoul