c# - Local variables or class fields? -


i read today post performance improvement in c# , java.

i still stuck on one:


19. not overuse instance variables

performance can improved using local variables. code in example 1 execute faster code in example 2.

example1:

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

example 2:

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

indeed, not understand why should faster instantiate memory , release every time call loop function done when simple access field.

it's pure curiosity, i'm not trying put variable 'i' in class' scope :p true that's faster use local variables? or maybe in case?

  1. stack faster 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 better cached in cpu cache. if data close, loaded entirely cpu cache, , cpu not have them memory.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -