Title: .NET Memory Consumption Question
Tags: .net;memory-management
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;
}
```


Here is the accepted answer: 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 vmartinez@example.net.


Here is another answer: You could look at the IL generated (using reflector) and see if it vmartinez@example.net. 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 vmartinez@example.net.

Comment for this answer: Yes, but if the IL is the same, then the code will do exactly the same thing.
Comment for this answer: The IL isn't the compiled code though. It's only an intermediary step.

Here is another answer: 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).

Comment for this answer: 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.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2010:00:10/28/10', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<.net><memory-management>', 'Title': '.NET Memory Consumption Question', 'ViewCount': 108, 'id': 4044379, 'user_AboutMe': '<p>I want to build software and relationships that change lives for the better.</p>\n', 'user_AccountId': 199222.0, 'user_DisplayName': 'Brad', 'user_Reputation': 15114.0, 'user_Views': 876.0, 'user_id': 444382.0}}