for (int i = 0; i < 1000000; ++i)
{
object = GetSomeObject (i);
*do stuff with object*
}
or
for (int i = 0; i < 1000000; ++i)
{
Object* object;
object = GetSomeObject (i);
*do stuff with object*
}
The second way it seems that I have to recreate the variable for every loop, but is this really true? Also, remember that a practical use would involve many variables being 'recreated'.
"[font="Courier New"]Object*[/font]" is a primitive type, so there's no cost for "creating" one every iteration.
If instead you had an "[font="Courier New"]Object[/font]" it would be different -- e.g.:class Object
{
public:
Object() {
//do something expensive here
}
~Object() {
//do something expensive here
}
};
...
for (int i = 0; i < 1000000; ++i)
{
Object object;//calls Object::Object() every iteration
I prefer the second method because it makes it obvious that each iteration has a new instance and that the instance is not supposed to be an output of the loop to be used afterwards.
If you're concerned about performance, try both and measure which is faster. If you can't measure the difference, then it doesn't which is 'faster.' My guess is that a good compiler optimizes both to be the same.
I think second one should perform better in a multithreaded code, because threads aren't too much happy with global variables. (Please correct me if I'm wrong.)
In C++ you should prefer initialization over assignment. for (int i = 0; i < 1000000; ++i)
{
Object* object = GetSomeObject(i);
*do stuff with object*
}
In C++ you should prefer initialization over assignment. for (int i = 0; i < 1000000; ++i)
{
Object* object = GetSomeObject(i);
*do stuff with object*
}
sorry to hijack, but why and where can I find more about initialization vs assignment?
https://github.com/cpgf/cpgf cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.
@procgen
Stack? It might end up in registers, as constants or eliminated entirely depending on the nature of SomeOtherFunction().
@OP
Modern compilers are extremely good. If you're worried about speed you'll want to be looking at the high levelalgorithms and data structures you are using. In your example, you might be able to avoid processing all 1,000,000 objects with a clever data structure that groups objects spatially, for example. This would blow any low level optimisations out of the water.
When you are doing such low level optimisations, you'll need to be profiling and looking at the assembly. Without doing so, you're effectively stumbling in the dark and hoping your program will be faster when you're done.