views:

63

answers:

3

Does either of these methods use more memory than the other or put a larger load on GC?

Option #1

LargeObject GetObject()
{
    return new LargeObject();
}

Option #2

LargeObject GetObject()
{
    LargeObject result = new LargeObject();
    return result;
}
+5  A: 

The heap memory usage of both methods is equal. There is tiny overhead in creation of the local variable in the second case but it shouldn't bother you. Variable will be stored on the stack and won't cause any additional pressure for GC. Also this additional variable might be optimized by the compiler or JIT (so it maybe not present in the code actually being executed by CLR).

Andrew Bezzub
It's unlikely that there will be any difference in the generated code in release mode. The JIT compiler will almost certainly remove the unnecessary temporary variable.
Jim Mischel
+1  A: 

You could look at the IL generated (using reflector) and see if it differs at all. Depending on the compilation optimization settings, #2 might store an extra value on the stack (for the result value), but that will only be an extra 4 or 8 bytes (if it's a class, which it should be!), and will not affect the GC at all.

thecoop
The IL isn't the compiled code though. It's only an intermediary step.
Winston Smith
Yes, but if the IL is the same, then the code will do exactly the same thing.
thecoop
+3  A: 

The compiler will generate IL that's equivalent to version 2 of your code, a virtual stack location is needed to store the object reference. The JIT optimizer will generate machine code that's equivalent to version 1 of your code, the reference is stored in a CPU register.

In other words, it doesn't matter. You get the exact same machine code at runtime.

Hans Passant