开发者

.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()
{
    Lar开发者_JAVA百科geObject 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜