Brad
Brad

Reputation: 15577

.NET Memory Consumption Question

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;
}

Upvotes: 1

Views: 115

Answers (3)

Hans Passant
Hans Passant

Reputation: 942438

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.

Upvotes: 3

Andrew Bezzub
Andrew Bezzub

Reputation: 16032

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).

Upvotes: 5

thecoop
thecoop

Reputation: 46168

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.

Upvotes: 1

Related Questions