代码之家  ›  专栏  ›  技术社区  ›  KoboldMines

Java脚本中函数与命名函数表达式的代码性能及差异

  •  -1
  • KoboldMines  · 技术社区  · 7 年前

    有时代码中有50k+行,应该对它们进行优化以使其更快地工作。这里我有一个关于函数的问题。我们知道这两者之间的区别:

    function f () {
      //code here
    }
    

    var f = function () {
      //code here
    }
    

    f();
    var f = function () {
      //code here
    }
    

    这将抛出一个错误。

    f();
    function f () {
      //code here
    }
    

    这很管用。

    我的问题是。这两个声明之间有什么根本的区别吗。在代码行超过50k的大型项目中,它会影响性能吗?

    3 回复  |  直到 7 年前
        1
  •  1
  •   skyboyer    7 年前

    实际上有一些不同 http://jsben.ch/SqczP

    带有基于变量声明的分支的性能提高了11%。

    但您的问题的实际答案是:不,除非您决定在大循环中声明函数,否则不会。即使这样,您也必须停止使用这种结构,而不是优化声明

        2
  •  0
  •   agravat.in    7 年前

    在执行任何代码之前加载函数声明。

    hoisted(); // logs "foo"

    function hoisted() { console.log('foo'); }

    以及

    函数表达式仅在解释器到达该行代码时加载。

    notHoisted(); // TypeError: notHoisted is not a function

    var notHoisted = function () { console.log('bar'); };

        3
  •  0
  •   Chris Li    7 年前
    f();
    var f = function () {
      //code here
    }
    

    var f;
    f();
    f = function () {
      //code here
    }