在Javascript中调用函数的成本或不是 [英] Cost of calling a function or not in Javascript

查看:166
本文介绍了在Javascript中调用函数的成本或不是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较:

if (myVariable) {
    doSomething()
}

function doSomething ()
{
    // Work goes here
}

vs

vs

doSomething();

function doSomething()
{
    if (myVariable) {
        // Work goes here
    }
}

ie我的问题是在函数之外进行检查并避免上下文切换(我认为这是正确的或者只是在功能里面做,因为它会产生如此小的差异?

ie My question is whether it's faster to do the check outside of the function and avoid a context switch (I think that's the right term) ) or just do it inside the function because it makes such a minor difference?

干杯。

推荐答案

它只是不重要(尽管第一种方法避免了一些工作,所以它应该更快,但数量可能低于统计噪音)。

It Just Doesn't Matter (although the first method avoids some work so it should faster, but by an amount which is probably less than statistical noise).

什么真正重要的是哪种方法最能代表逻辑。经验法则是函数中的每个语句都应该处于大致相同的抽象层次上。条件表达式是否比函数调用抽象更多或更少?

What really matters is which method best represents the logic. Rule of thumb is that every statement in a function should be on about the same level of abstraction. Is the conditional expression more or less abstract than the function call?

这篇关于在Javascript中调用函数的成本或不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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