简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM