问题
A simplified example:
function shorten(string) {
return string.slice(0, 3);
}
const today = "Friday";
if (shorten(today) === "Fri") {
console.log("Oh yeah it's " + shorten(today));
}
shorten(today)
is called twice here, which makes me feel bad. I believe we all run into this situation every day, and what we do is store the the value of shorten(today)
in a variable first, then use that variable twice.
My question is: are modern JS engines smart enough so that I actually don't need to worry about it?
回答1:
If you run shorten
multiple times, the V8 engine has a JIT compiler that will optimize that piece of code so it runs faster the next time.
When it runs into the same function call for the 2nd time, maybe it's able to realize it has just did the same calculation, and still have the result in memory
What you described is known as memoization, and V8 doesn't do that. However, there are libraries out there (e.g. fast-memoize) that does.
But you best bet is still to store the result of the computation in a variable and reference it.
回答2:
When I execute a simple JS function twice in a row, does it cost twice the computing power?
Yes. Consider Why is using a loop to iterate from start of array to end faster than iterating both start to end and end to start?
are the modern JS engines smart enough so that I actually don't need to worry about it?
No. No engine can reliably predict the return value of a JavaScript function call. See Has it been mathematically proven that antivirus can't detect all viruses? Can a regular expression be crafted which determines the return type of a function?
来源:https://stackoverflow.com/questions/54601304/when-i-execute-a-simple-js-function-twice-in-a-row-does-it-cost-twice-the-compu