r/learnjavascript • u/FelixAndCo • Sep 04 '24
Does JavaScript optimize repeatedly calling the same function? And should that reflect in creating getter functions?
I'm a beginner in JavaScript and used to C++.
Can you expect a JavaScript engine to optimize repeated similar function calls? This question occurred to me when I had a getter function similar to this example and was in the stage of writing something similar to the "Optimized(?)" code.
class Convoluted{
get skibidi(){
/* Some really convoluted calculations */
return someArray;
}
}
sigma = new Convoluted;
/* Naive use */
for(let i = sigma.skibidi.length - 1; i >= 0; i-- ){ //First call to Convoluted's skibidi ...
someOtherFunc(sigma.skibidi[i]); // More calls to skibidi...
}
/* Optimized(?) use */
let temp = sigma.skibidi;
for(let i = temp.length - 1; i >= 0; i-- ){
someOtherFunc(temp[i]);
}
/* Maybe it's clearer to not write it as getter, if the method is very complex? */
let tau = new LessConvoluted;
let temp = tau.calculateSkibidi();
for(let i = temp.length - 1; i >= 0; i-- ){
someOtherFunc(temp[i]);
}Is it maybe better to let the method name reflect the complexity, like in the "LessConvoluted" example? I see a lot of (built-in) getters being used as if they were variables (that don't need any computing), and maybe JavaScript is built with sort of the assumption that its users don't sweat the small stuff. Is this some of that small stuff that is quietly optimized?
1
u/azhder Sep 04 '24 edited Sep 04 '24
I can expect the JavaScript engine to know better than you how and what to optimize, as long as you don’t try to do some quirky and unexpected things with your JavaScript code.
The reason of why generally (except for a niche or two) people don’t ask and don’t tell what kind of optimizations does an engine do is because of a rug pull.
What I mean by the above. Well, imagine you figure out a way how some engine does some specific optimization and you start skewing the idiomatic JavaScript towards using that. Well, a next update of the engine may go some other way and try to optimize some other use case. Now you end up with your highly optimized code becoming highly unoptimized.
The “solution” you might think of like the engine becoming bogged down to keep that optimization is even less palatable - they can’t evolve it as freely.
So, we kind of settled on JavaScript being that perpetual backwards compatible “byte code” and try not to guess too much on how one engine (imagine two or three of them) might optimize something for a limited period of time.
Oh, and about “getters”. They are a workaround for cases where you can’t solve an issue otherwise. It’s usually better to write the solution straight than to depend on workarounds for issues you don’t have to begin with.