简体   繁体   English

.NET内存消耗问题

[英].NET Memory Consumption Question

Does either of these methods use more memory than the other or put a larger load on GC? 这两种方法中的任何一种是否使用的内存都比其他方法要大,或者会给GC带来更大的负担?

Option #1 选项1

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

Option #2 选项#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. 变量将存储在堆栈中,不会对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). 同样,此附加变量可能由编译器或JIT优化(因此它可能不存在于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. 编译器将生成与您的代码版本2等效的IL,需要一个虚拟堆栈位置来存储对象引用。 The JIT optimizer will generate machine code that's equivalent to version 1 of your code, the reference is stored in a CPU register. JIT优化器将生成与您的代码版本1等效的机器代码,引用存储在CPU寄存器中。

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. 您可以查看生成的IL(使用反射器),看看它是否完全不同。 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. 根据编译优化设置,#2可能会在堆栈上存储一个额外的值(作为result值),但这只会额外增加4或8个字节(如果它是一个类,应该是!),并且会完全不影响GC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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