Static constant versus constant in a function that is called repeatedly

There are a couple of things that affect the answer:

  • First, as long as the value is const it will almost certainly be optimized out in any case. That means that the resulting code will most likely be the same.
  • Second, static members are stored elsewhere which means less locality and probably a cache miss.
  • Third, the cost of initialization depends on the type. In your case, for an int, the cost of initialization is basically nonexistent. For more complex user-defined types, it may be huge.

So the answer is, in cases simple enough for the compiler to figure them out and optimize, it makes zero difference. In your example that would almost certainly be the case.

As long as the variable has a type that is easy and cheap to construct, prefer non-static to avoid the cache miss.

If the type is expensive to construct, you might want to use static.

And of course, last, and most importantly of all:

Don’t trust our guesswork. If you are concerned about performance, there is only one correct course of action:

  • Measure it, to verify that it is actually a problem
  • Measure the performance of each possible solution
  • Pick the solution that results in the best performance.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)