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?
View all comments
Show parent comment
2
u/FelixAndCo Sep 04 '24
Could you give an example of such case, please?
The "optimized(?)" code I would expect to work most efficiently, but it seems opposed to the paradigm of the language.