I understand that the const modifier allows the compiler more freedom when reading the associated variable versus the non-const version. I also understand that const is normally used to promote healthy coding styles and not necessarily as a optimization speed boost.
My question is this: In practice, does using the const modifier ever significantly speed up a piece of code?
I have done some timings on my own problem (making a 2D array class) and there was, sadly, little to no speed gain in using the const modifier for the array bounds versus allowing the array to be resized.
const declares a variable 'read-only' so you cant change it. It is usefull in classes and function parameters so the user knows the function or method wont change the contents of the variable.
For arrays: const int arr[10] declares an array of 10 unchangable integers, however int const * arr = new int[10]; declares a constant pointer of normal integers, which means that you wont be able to change the pointer any more. What I'm saying is that your array was probably able to be resized, but its values were constant.
...however int const * arr = new int[10]; declares a constant pointer of normal integers...
Actually it does not. It defines an array of constant integers and is equivalent to constint * arr = newint[10]. You probably meant to write int * const arr = newint[10]
In general no. const may allow the compiler to make some small optimizations in specific cases, but in general you will not see an appreciable change in performance.
What about the use of inline functions within a class. Would expanding inline make your program faster when the mameber function is called, than if you had used the scope resolution operator and define the function outside of your class.
If the body of the function is available to the compiler at the call site, the compiler can inline the function. The only ways this happens are:
1) declare the function inline and implement it in the header file, in which case any .cpp calling the function can
benefit from inlining (if the compiler chooses); [Note that there is no difference at this point between implementing
the function within the class declaration or implementing it outside the class declaration but still in the header.]
2) if the function is declared in the header file but implemented in foo.cpp, then only calls to the function in foo.cpp can benefit from inlining (since the compiler can see the body of the function while compiling other code inside foo.cpp).
Inlining allows the compiler to avoid generating stack frames for the call. Although setting up a stack frame is typically only a few instructions, done enough times the execution time savings can add up.