当我连续执行两次简单的JS函数时,它的计算能力是否会增加一倍? [英] When I execute a simple JS function twice in a row, does it cost twice the computing power?

查看:46
本文介绍了当我连续执行两次简单的JS函数时,它的计算能力是否会增加一倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简化的示例:

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)的值存储在一个变量中,然后使用该变量两次.

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.

我的问题是:现代JS引擎是否足够聪明,以至于我实际上不必担心它?

My question is: are modern JS engines smart enough so that I actually don't need to worry about it?

推荐答案

如果多次运行 shortening ,则V8引擎具有 JIT编译器,它将对该部分进行优化代码,因此下次运行速度更快.

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

您所描述的被称为记忆力,而V8则不这样做.但是,那里有一些库(例如 fast-memoize )

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.

这篇关于当我连续执行两次简单的JS函数时,它的计算能力是否会增加一倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆