当我连续两次执行一个简单的 JS 函数时,是否会消耗两倍的计算能力?

When I execute a simple JS function twice in a row, does it cost twice the computing power?

一个简化的例子:

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)这里被调用了两次,心情不好。我相信我们每天都会 运行 遇到这种情况,我们所做的就是先将 shorten(today) 的值存储在一个变量中,然后使用该变量两次。

我的问题是:现代 JS 引擎是否足够智能以至于我实际上不需要担心它?

When I execute a simple JS function twice in a row, does it cost twice the computing power?

是的。考虑

are the modern JS engines smart enough so that I actually don't need to worry about it?

没有。没有引擎可以可靠地预测 JavaScript 函数调用的 return 值。参见 Has it been mathematically proven that antivirus can't detect all viruses?

如果你 运行 shorten 多次,V8 引擎有一个 JIT 编译器 会优化那段代码,所以它 运行 下次会更快。

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

您描述的内容称为 memoization,而 V8 不会这样做。但是,有些库(例如 fast-memoize)可以。

但最好还是将计算结果存储在变量中并引用它。