简体   繁体   English

局部变量或类字段?

[英]Local variables or class fields?

I read today a post about performance improvement in C# and Java. 我今天读了一篇关于 C#和Java 性能改进文章

I still stuck on this one: 我还是坚持这个:


19. Do not overuse instance variables 19.不要过度使用实例变量

Performance can be improved by using local variables. 使用局部变量可以提高性能。 The code in example 1 will execute faster than the code in Example 2. 示例1中的代码执行速度比示例2中的代码快。

Example1: 例1:

public void loop() {
    int j = 0;
    for ( int i = 0; i<250000;i++){
        j = j + 1;
    }
}

Example 2: 例2:

int i;
public void loop() {
    int j = 0;
    for (i = 0; i<250000;i++){
        j = j + 1;
    }
}

Indeed, I do not understand why it should be faster to instantiate some memory and release it every time a call to the loop function is done when I could do a simple access to a field. 实际上,我不明白为什么在我可以对字段进行简单访问时,每次调用loop函数时实例化一些内存并释放它应该更快。

It's pure curiosity, I'm not trying to put the variable 'i' in the class' scope :p Is that true that's faster to use local variables? 这是纯粹的好奇心,我不是试图将变量'i'放在类的范围内:p是否真的使用局部变量更快? Or maybe just in some case? 或者只是在某些情况下?

  1. Stack faster then Heap. 比堆更快堆栈。

     void f() { int x = 123; // <- located in stack } int x; // <- located in heap void f() { x = 123 } 
  2. Do not forget the principle of locality data . 不要忘记地方数据的原则 Local data should be better cached in CPU cache. 应该在CPU缓存中更好地缓存本地数据。 If the data are close, they will loaded entirely into the CPU cache, and the CPU does not have to get them from memory. 如果数据接近,它们将完全加载到CPU缓存中,并且CPU不必从内存中获取它们。

The performance is down to the number of steps required to get the variable. 性能低至获取变量所需的步骤数。 Local variable addresses are known at compile time (they are a known offset on the stack), to access a member you load the object 'this' to get the address of the actual object, before you can get the address of the member variable. 本地变量地址在编译时是已知的(它们是堆栈上的已知偏移量),用于访问加载对象“this”的成员以获取实际对象的地址,然后才能获取成员变量的地址。

Even if it will be, there will be almost non measurable difference in this cases. 即使它会,但在这种情况下几乎没有可衡量的差异。 Probabbly in first case, there is some optimization done on processor registry level, but again: Probabbly在第一种情况下,有一些优化的处理器注册表层面完成,但再次:

  • it's almost irrelevant 这几乎无关紧要
  • and what is more important, often unpredictable. 更重要的是,往往是不可预测的。

In terms of memory, it's exactly the same, there is no any difference. 在记忆方面,它完全相同 ,没有任何区别。

The first case it generaly better: as you declare variable there were it's imediately used, which is commonly used good pattern, as it's 第一种情况它通常更好:当你声明变量时,它是立即使用的,这是常用的良好模式,因为它是

  • easy to understand (scopes of responsibilities) 易于理解(职责范围)
  • easy refactor 简单的重构

In C# another minor difference is the number of generated MSIL instructions (I guess it's similar in Java). 在C#中,另一个细微差别是生成的MSIL指令的数量(我猜它在Java中类似)。

It takes two instructions to load an instance field: 加载实例字段需要两条指令:

ldarg.0                 // load "this" reference onto stack
ldfld   MyClass.myField // find the field and load its value

...but it only takes one instruction to load a local variable: ...但只需要一条指令来加载局部变量:

ldloc.0                 // load the value at index 0 from the list of local variables

I suspect there's very little difference, however in the case where the variable is a member of the object, each access requires an indirection via this (effectively), whereas the local variable does not. 我怀疑差异很小,但是在变量是对象成员的情况下,每次访问都需要通过this (有效)进行间接,而局部变量则不需要。

More generally, the object has no need for a member i , it's only used in the context of the loop, so making it local to its use is better in any case. 更一般地说,对象不需要成员i ,它只在循环的上下文中使用,因此在任何情况下使其在本地使用都更好。

I tested a calculation with 500,000 iterations where I used about 20 variables locally and one that does it with fields. 我测试了500,000次迭代的计算,其中我在本地使用了大约20个变量,并且使用了字段。 The local variable test was about 20 milliseconds and the one with fields was about 30 milliseconds. 局部变量测试大约是20毫秒,带有字段的测试大约是30毫秒。 A significant performance gain when you use local variables. 使用局部变量时,性能显着提高。

Whether the performance difference is relevant, depends on the project. 性能差异是否相关,取决于项目。 In your average business application the performance gain may not be noticeable and it is better to go for readable / maintainable code, but I am working on sound synthesis software where nano-optimizations like this actually become relevant. 在您的平均业务应用程序中,性能增益可能不明显,最好是可读/可维护代码,但我正在开发声音合成软件,其中像这样的纳米优化实际上变得相关。

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

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