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

标签 javascript google-chrome v8

一个简化的例子:

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 引擎是否足够智能,以至于我实际上不需要担心它?

最佳答案

如果您多次运行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

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

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

关于javascript - 当我连续两次执行一个简单的 JS 函数时,是否会消耗两倍的计算能力?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601304/

相关文章:

css - chrome padding percentage + width percentage 不相加

javascript - 输入的值即使不符合要求也被发送

javascript - 我无法提交表格

javascript - 在 Node.js 中迭代大量 JSON 文件

ajax - 加载外部数据时,控制台显示: XHR finished loading

ajax - Chrome数据压缩代理和DWR

javascript - 在 C#/Javascript.net/V8 上运行 Less.js

javascript - 如何在 Chrome 中正确读取和修复 Web 应用程序的内存使用情况

node.js - WebStorm V8 分析 : (Stacktrace cut)?

javascript - Typescript 错误 "Property does not exist on type ' JSX.IntrinsicElements'"使用 native Web 组件时