stack variables and loops

Diego Novillo dnovillo@google.com
Wed Mar 19 13:18:00 GMT 2008


2008/3/19 Wesley Smith <wesley.hoke@gmail.com>:

>  Vec3 *v = vectors;
>  for(int i=0; i < 100; i++) {
>        Vec3 v_rand;
>         v_rand.random();   //make a random vector;
>
>           *v++ += v_rand;
>  }
>
>
>  /////example 2
>
>  Vec3 *v = vectors;
>   Vec3 v_rand;
>  for(int i=0; i < 100; i++) {
>         v_rand.random();   //make a random vector;
>
>           *v++ += v_rand;
>  }
>
>
>  Clearly there are scope differences between the 2 examples, but in
>  terms of performance, how do compilers handle these situations.

The first version needs to have a ctor and dtor call invoked on every
iteration of the loop.  Depending on what they do that will slow the
code down.  If you insert a printf() call in Vec3's constructor and
destructor you'll see the difference.  With GCC 4+ you can also use
-fdump-tree-gimple to get a C-like representation of your program.


Diego.



More information about the Gcc-help mailing list