in JS it a good practice to create a variable, for reusing, instead of access the value in a deep object structure:
for (var i = 0, l = arr.length; i < l; ++i) {
var someValueINeedOftenHere = arr[i].path.to.value;
// do several things with this var..
}
So instead of finding the value in this deep object structure, we store it locally and we can reuse it over and over again. This should be a good practice, not only because it lets you write cleaner code, but also because of performance.
So, when I am writing C++ code, and I've to iterate over a vector, which holds a lot of structs / objects. Is then the same, or it doesn't matter?
Generally speaking, in C/C++ it doesn't matter. In C and C++, the memory layout of every structure is known at compile-time. When you type arr[i].path.to.value
, that's going to be essentially the same as *(&arr[0] + i * (something) + offset_1 + offset_2 + offset_3)
, and all that will get simplified at compile-time to something like *(&arr[0] + i * (something) + something)
. And those something
's will be computed by the compiler and hard-coded into the binary, so effectively looking up arr[i].path.to
is not faster than arr[i].path.to.value
.
This is not mandated by the standard or anything as far as I know, but it's how most compilers will actually work.
If you want to be sure in some specific case, you can look at godbolt and see what assembly it cooks up: http://gcc.godbolt.org/
Note that I'm assuming that when you make the local variable, you are taking a reference to the value arr[i].path.to.value
, which is most similar to what you do in javascript. If you actually copy the value to a new variable then that will create some copying overhead. I don't think that copying it would be advantageous w.r.t. cache misses unless the usage pattern is pretty complicated. Once you access arr[i].path.to.value
once, all the stuff around it is going to be in the cache, and there's no reason that copying it onto the stack would make anything faster.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments