I've recently discovered how to use reference arguments in an actually useful manner, but was surprised when I realized a large difference in speed between it and the use of pointers.
I had a program which rendered an image with a dozen or so functions all running by reference. Noticing a large load-time (around 6 seconds), I went on a limb and rebuilt them all using pointers instead. Now the program runs at around 3.5 seconds.
Is this something to do with the differences (still unclear to me) between references and pointers? Is it my operator[] in the first example that is somehow inefficient (with its whopping one line of code)?
Obviously, this is a program that uses these functions a few hundred thousand times, so any performance boost is appreciated.
Those aren't the same...the reference one accesses the operator[] of vector (which is a function call at runtime since it is not inline), whereas the pointer one accesses a member called v and then uses the operator[] on that (which is all done at compile time).
Anyway, make your vector:: operator inline, and make the int you are passing const. That should make them more equal.
As far as I know, the compiler makes an assessment and decides itself whether or not to inline a function at compile-time. I didn't think that needs to be made explicit.
To give the compiler the best chance of inlining, you should declare and implement the function in the header file.
Otherwise, no, it is unlikely if not impossible (depending upon code structure) that the compiler will silently
inline it for you.
1) It might be. I know in VC++ there are settings (optimization settings I believe) that tell the compiler to inline or not. If you are compiling in debug, there is no inlining done.
2) Yes, and put the function body in the header file (the same one you declaring it inline in).
That's it, probably. I'm spending most of my time debugging (for performance! How ironic), so I'm keeping it all in Debug build. That's probably why it's not inlining the operator-call. Does it inline in debug mode if you make it explicit, though?