🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Hundreds of times less performance when accessing an array in a loop

Started by
3 comments, last by Juliean 2 years, 8 months ago

Two small code fragments, in one the array is declared in the header, in the other - in the function. In the first case performance drops like hell, in the second case it doesn't. VC++

This is how it slows down:

--- programm.h

class programm {
  int array[100500];

  void func();
}

--- programm.cpp

programm::func() {
  for()
    for()
      if ()
          int offset = ...
          int var = ...
          array[offset] = var;

}

Everything is fast: we have collected for you a list of porn sites which are the best for viewing porn in mobile mode https://bestpornsites.mobi

--- programm.h

class programm {
  void func();
}

--- programm.cpp

programm::func() {

  int array[100500];
  for()
    for()
      if ()
          int offset = ...
          int var = ...
          array[offset] = var;

}

All the difference is in the place where the array is declared.

How so, what can it be connected to?

Advertisement

Looks like a contrived example. Is this an assignment?

🙂🙂🙂🙂🙂<←The tone posse, ready for action.

If your question is “why does this happen”, you should take a look at the difference in declaration of the array. There is a huge and significant difference in the meaning between declaring an array in code vs. in function

In general, accessing a member-variable is going to be slower than a local, simply because it has to load the array with an addition indirection from the “this”-pointer (and the potential of aliasing of the pointer). However, 100 times slower is nowhere near where this should happen.

So, if your shown code is close to reality, here's what I guess is going on: Since you don't seem to use the array anywhere after the assignment, the compiler is most likely optimizing away the local-variable version of the array entirely (you don't even seem to initialize the array at all). However, when you store values inside a class-member variable, it cannot do that, since this class-member might be accessed anyway further down the line. Thus the local variable is probably just doing nothing, while the class-member is actually executing the loops and assignments, thus the 100-times difference in performance.

This topic is closed to new replies.

Advertisement