rodneys@gmx.de wrote:[color=blue]
> Hi,
>
> please take a look to this sample code:
>
> class MyClass {
> private:
> static int length ;
> public:
> static void setLength(int newLength) ;
> void do() ;
> }
>
> int MyClass::length ;
>
> void MyClass::setLength(int newLength) {
> length=newLength ;
> }
>
> void MyClass::do() {
> for(int i=0;i<length;i++) {
> // some simple floating point additions and multiplications ...
> }
> }
>
> I expected that the compiler (Microsoft EVC 4 for ARM, full
> optimization)
> would optimize the for-loop of the method "do" to
> register int t=length ;
> for(int i=0;i<t;i++) {
> ...
> }
> But this does not happen. Instead, the generated machine code
> refetches "length" in each iteration of the for-loop. Why?
> Does the compiler "fear" that another thread could call "setLength"
> while the for-loop runs? "length" is *not* declared volatile.
>
> Is there a formal specification how long a compiler is allowed to cache
> non-local variables in registers? For example, can code like
> a = length ;
> b = length ;
> always be expected to be optimized to
> register int t=length ;
> a=t ;
> b=t ;
> ?
>
> rs
>[/color]
rule of thumb is to cache any global variable in a local variable to
ease optimization for the compiler. If a register is available, it will
be allocated for the local variable. If none is available, the local
varialbe will most likely be allocated on stack and therefore will most
likely have a better cache behaviour than its global counterpart. The
compiler might even be capable of eliminating the local variable.
I cannot say what the reason for missing optimization is your case,
because you omitted the contents of the for loop. But I recomend to
allocate a local variable that is the copy of the object attribute.
HTH,
Tom