Is JavaScript caching calls to Object.keys() in functional filter(), every() etc.?

Tooster :

Does it influence performance if I cache a call to Object.keys() in a variable when repeteadly checking it's content inside every(), filter(), any() etc. functions ? Does the JS engine perform inline caching in this case?

X = {/*...*/};
t = [/*...*/];
f = key => {/*...*/}; // somehow transforms keys of X

// we want to check if all elements of t are the transformed keys of X
keys = Object.keys(X).map(f);
result = t.every(a=>keys.includes(a)); // <──────── is this faster than this ?
result = t.every(a=>Object.keys(X).map(f).includes(a)); // <──────────────┘

// same with filtering etc.
t = t.filter(a => !Object.keys(X).includes(a)); // discarding elements from t that are not keys in X

The answer will influence my coding practice, I'd much rather use the second, more compact version, because it can be used in a one-line lambdas and is easier to look at without jumping to definitions.

Pointy :

Unless your code performs the operations many thousands of times, it won't matter. However making a function call (to Object.keys()) and in the process instantiating a new array will always use more resources than not doing that.

It's more important for your code to be understandable and maintainable than optimally composed in almost all cases.

It's also a really good idea to not rely on supposed optimization behaviors inside the JavaScript runtime(s). Those may change. It's OK to simply trust that somebody maintaining the runtime has performance as their full-time job.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29981&siteId=1