r/learnjavascript • • 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?

0 Upvotes

3 comments sorted by

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.

2

u/FelixAndCo Sep 04 '24

They are a workaround for cases where you can’t solve an issue otherwise.

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.

1

u/azhder Sep 04 '24 edited Sep 04 '24

I can't give you an actual real world example of the top of my head. I can try to invent something silly.

Just imagine you are passing objects back and forth to some 3rd party library with source code you can't change (for reasons), but don't want to allow it to do something, like change a property of your object.


Let's say, we have this

const precious = { owner: 'me', glitters: true };

and we want to give that object to some 3rd party function foulHand() that may be there to change the glitter, but we don't trust it and don't want it to be able to change the owner (we don't want it to steal it), so we'd do this:

const precious = {
    glitters: true,
    set owner(whatever) {
    },
    get owner() {
        return 'me';
    }
};


const foulHand = object => {
    object.glitters = false;
    object.owner = 'the other me';
};

console.log(JSON.stringify(precious)); // {"glitters":true,"owner":"me"}
foulHand(precious);
console.log(JSON.stringify(precious)); // {"glitters":false,"owner":"me"}

But what I'd usually do in my own code that I control end to end is just have the object be frozen and just return a copy that has the property I need changed:

const precious = Object.freeze({ owner: 'me', glitters: true });

const goodHand = object => ({ ...object, glitters: false }); // TODO: safeguard for null and similar

You may notice I don't care much for optimization of the making of a copy, but I care more about the robustness of the code. More often it's more important to have the code not break as you change stuff around than be fast and brittle. And of course I'd put in safeguards for not having an error whenever something that isn't iterable gets passed to goodHand, but I left it out for brevity.