局部变量或类领域? [英] Local variables or class fields?

查看:131
本文介绍了局部变量或类领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我阅读有关后。性能改进在C#和Java



我仍然停留在这一个:






19。不要过度使用实例变量



性能可以通过使用本地变量加以改进。例1中的代码将执行比例2中的代码更快



例1:

 公共无效循环(){
INT J = 0;
的for(int i = 0; I< 250000;我++){
J = J + 1;
}
}



例2:

  INT I; 
公共无效循环(){
INT J = 0;
为(i = 0; I< 250000;我++){
J = J + 1;
}
}






事实上,我不明白为什么它应该更快实例化一些内存和每次释放它调用循环功能完成后,我可以做一个简单的访问。字段



这是纯粹的好奇心,我不是试图把变量'我'在类范围:p
是真的,会更快使用局部变量?或者,也许只是在某些情况下?


解决方案

  1. 堆栈的速度,然后堆。

     无效F()
    {
    INT X = 123; //< - 位于堆栈
    }

    INT X; //< - 位于堆
    无效F()
    {
    X = 123
    }


  2. 不要忘局部性数据的原则。本地数据应该在CPU缓存缓存更好。如果数据接近,它们将完全装载到CPU高速缓存,并且CPU不必从存储器得到它们。



  3. I read today a post about performance improvement in C# and Java.

    I still stuck on this one:


    19. Do not overuse instance variables

    Performance can be improved by using local variables. The code in example 1 will execute faster than the code in Example 2.

    Example1:

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

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

    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? 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. If the data are close, they will loaded entirely into the CPU cache, and the CPU does not have to get them from memory.

    这篇关于局部变量或类领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆