Is it better/faster to have class variables or local function variables?

c++, optimization

Solution

By limiting the scope of your variables, you are giving more opportunity to the compiler optimiser to rearrange your code and make it run faster. For example, it might keep the values of those variables entirely within CPU registers, which may be an order of magnitude faster than memory access. Also, if those variables were class instance variables, then the compiler would have to generate code to dereference `this` every time you accessed them, which would very likely be slower than local variable access.

As always, you should measure the performance yourself and try the code both ways (or better, as many ways as you can think of). All optimisation advice is subject to whatever your compiler actually does, which requires experimentation.

Problem

Ok I know the title doesn't fully explain this question. So I'm writing a program that performs a large number of calculations and I'm trying to optimize it so that it won't run quite so slow. I have a function that is a member of a class that gets called around 5 million times. This is the function: ``` void PointCamera::GetRay(float x, float y, Ray& out) { //Find difference between location on view plane and origin and normalize float vpPointx = pixelSizex * (x - 0.5f * (float)width); float vpPointy = pixelSizey * (((float)height - y) - 0.5f * height); //Transform ray to camera's direction out.d = u * vpPointx + v * vpPointy - w * lens_distance; out.d.Normalize(); //Set origin to camera location out.o = loc; } ``` I'm wondering if it is better/faster to declare the variables vpPointx and vpPointy in the class than to declare them each time I call the function. Would this be a good optimization or would it have little effect? And in general, if there is anything here that could be optimized please let me know.

Original source

Related problems