I’m new to c++ (and SO) so sorry if this is obvious.
I’ve started using temporary arrays in my code to cut down on repetition and to make it easier to do the same thing to multiple objects. So instead of:
MyObject obj1, obj2, obj3, obj4;
obj1.doSomming(arg);
obj2.doSomming(arg);
obj3.doSomming(arg);
obj4.doSomming(arg);
I’m doing:
MyObject obj1, obj2, obj3, obj4;
MyObject* objs[] = {&obj1, &obj2, &obj3, &obj4};
for (int i = 0; i !=4; ++i)
objs[i]->doSomming(arg);
Is this detrimental to performance? Like, does it cause unnecessary memory allocation? Is it good practice? Thanks.
In general you just shouldn’t worry about performance at this level. Very often the things that end up being performance problems turn out to be completely different from what you might expect, especially if you don’t have a lot of experience with performance optimization.
You should always think about writing clear code first, and if performance matters then you should think about it in algorithmic terms (i.e., big-O). Then you should measure performance and let that guide where you spend your effort at optimization.
Now, you can make the code even clearer and more straightforward if you avoid the intermediate array and just use an array for the original objects:
But no, an optimizing compiler should generally have no problem with this.
For example, if I take the code:
and produce LLVM IR (because it’s more compact than actual assembly), I get the following with
-O3.At
-O3the loop gets unrolled and the code is identical with the original version. With-Osthe loops don’t get unrolled, but the the pointer indirection and even the arrays disappear because they’re not needed after inlining: