javascript - Javascript 回调模式示例 - 它真的更高效吗?

标签 javascript performance design-patterns callback

我在网上读到一篇book 。它给出了一个回调模式示例如下。

var findNodes = function () {
    var i = 100000, // big, heavy loop
        nodes = [], // stores the result
        found; // the next node found
    while (i) {
        i -= 1;
        // complex logic here...
        nodes.push(found);
    }
    return nodes;
};
var hide = function (nodes) {
    var i = 0, max = nodes.length;
    for (; i < max; i += 1) {
        nodes[i].style.display = "none";
    }
};

// executing the functions
hide(findNodes());

据说这样效率不高,因为它循环找到的节点两次,下面的代码效率更高。

// refactored findNodes() to accept a callback
var findNodes = function (callback) {
    var i = 100000,
        nodes = [],
        found;

    // check if callback is callable
    if (typeof callback !== "function") {
        callback = false;
    }

    while (i) {
        i -= 1;

        // complex logic here...

        // now callback:
        if (callback) {
            callback(found);
        }

        nodes.push(found);
    }
    return nodes;
};
// a callback function
var hide = function (node) {
    node.style.display = "none";
};

// find the nodes and hide them as you go
findNodes(hide);

但是,它们都是 O(n),并且调用函数的开销可能很大,这导致 findNodes() 中的每次迭代(带有回调)需要更多时间。所以我想知道这个修改是否真的如作者所说的那样有所不同。我该如何衡量这两种工具的成本?

最佳答案

根据数组的大小,仅循环一次的示例可能会更高效。

但是,您的担忧是正确的。特别是在较旧的 JS 引擎中,函数调用的开销很大。

与所有性能优化一样,这是您应该衡量的内容。使用分析器测试代码以查找瓶颈,然后进行优化,然后重新运行分析以了解其是否具有积极效果。

关于javascript - Javascript 回调模式示例 - 它真的更高效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11222505/

相关文章:

javascript - 如何在 ProtoType 中使用 Promises *around* 回调进行方法链接

javascript - 如何在 Yii 框架中使用表单添加 "Novalidate"。我正在使用 Angularjs

performance - 我怎样才能加速这个 MySQL 查询?

java - 将多个@Service 和@Repository 类分组到包装器中是一种反模式吗?

c++ - 随机数发生器 : Should it be used as a singleton?

java - 如何从数据库访问代码中抽象出业务逻辑和对象定义?

javascript - Angular 1.6,$compileProvider 和测试

javascript - 自定义选项更新 Magento 产品图像

performance - 有没有应用机器学习来提高代码性能的例子?

c# - 不必要的大括号会降低性能吗?