Software Engineering
javascript performance variables
Updated Sun, 02 Oct 2022 23:10:21 GMT

Does it always take the same amount of time to retrieve the same thing from collection?


for example:

const arr = [1,2,3,4];
const coordinate = [arr[0] + 2, arr[0] + 1];

here arr[0] is written out twice, when the code is executed would it literally go and find same value twice or would it remember it?

Does it matter that arr[0] in example above is used in the same expression? What if I would use arr[0] in the beginning of the file and at the end of the file?

Would it make sense to put arr[0] into a variable for performance?




Solution

It depends.

Some compilers or runtimes (since you tagged this JavaScript) may be able to optimize this, and will sometimes choose to do that. Future versions may choose differently. Hardware may be able to optimize it so that the second retrieval runs faster even if your language runtime is going through the same motions.

But you can't really rely on it. With compilers you can run them and inspect the results to see if it was optimized. With runtime optimizations, you don't even have that option - even if its optimized on your machine, that's no guarantee for the next guy, or even the next run.

If you know that the lookup is expensive (which is unlikely in your simple example), you should cache it yourself. If it's not expensive, save the effort for something that is.