这个Javascript函数有效吗?

时间:2012-04-20 06:36:28

标签: javascript performance

我有一个节点列表,它们是html li元素

<ul id="nodesList">
   <li id="node_1">Node 1</li>
   <li id="node_2">Node 2</li>
   <li id="node_3">Node 3</li>
   <li id="node_4">Node 4</li>
   <li id="node_5">Node 5</li>
</ul>

我有一个管理这些节点的javascript函数

(function (nodesManager) {
    var nodes = [];
    nodesManager.requestNode = function(id) {
        if (nodes[id]) {
            return nodes[id];
        }

        nodes[id] = new Node(id);
        return nodes[id];
    }
} (window.nodesManager = window.nodesManager || {}));

var Node = function(id) {
    instance = this;

    var node = $("#node_" + id);

    this.changeName = function(newValue) {
        node.text(newValue);
    };

    // and other nodes specific functions

    var _properties = null;
    this.getProperties = function () {
        if (_properties !== null)
            return _properties;

        var response = null;
        $.ajax({
            cache: false,
            async: false,
            type: "GET",
            url: '/Nodes/NodeProperties', // json object { "dateCreated": "10 minutes ago", "createdBy": "Mike" }
            data: { node_Id: id },
            success: function (data, textStatus) {
                if (data.hasError) {
                    alert(data.message);
                } else {
                    response = data;
                }
             },
             error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('ajax error');
             }
        });
        _properties = response;

        return _properties;
    };
        this.resetProperties = function () {
            _properties = null;
        };
    }


$("#nodesList").delegate("li", "click", function() {
    var node_Id = $(this).attr("id").replace("node_", "");

    var newNodeName = "I am a new value";
    nodesManager.requestNode(node_Id).changeName(newNodeName);
});

我的问题是,如果在Node对象中使用changeName函数会影响性能吗?

是否为用户选择的每个节点创建了?

将它放在nodesManager函数中是否更好,所以它只被实例化一次?或者这没关系...

对我来说非常重要

function getNodeCreatorUserName(id) {
    var properties = nodesManager.requestNode(id).getProperties();
    var userName = properties.createdBy;

    // do something with userName
};
function getNodeDateCreated(id) {
    var properties = nodesManager.requestNode(id).getProperties();
    var dateCreated = properties.dateCreated;

    // do something with dateCreated
};

getNodeCreatorUserName("1"); 
getNodeDateCreated("1");     // No server side call will be made because properties are already stored in Node object

3 个答案:

答案 0 :(得分:1)

Node已在window中定义,您可能应该将其称为其他内容。

尝试这样的事情:

function MyNode (id) {
   this.node = $("#node_" + id);
}

MyNode.prototype.changeName = function(newValue) {
    this.node.text(newValue);
};

答案 1 :(得分:1)

至于您对性能问题的关注(请记住,对于少量节点而言差异几乎不明显),您应该选择原型而不是关闭,因为它们是(最多> 50%) )更快,见:

Javascript prototype operator performance: saves memory, but is it faster?

http://blogs.msdn.com/b/kristoffer/archive/2007/02/13/javascript-prototype-versus-closure-execution-speed.aspx

http://ejohn.org/blog/simple-class-instantiation/

答案 2 :(得分:1)

如果你真的想挤压周期......

(function (nodesManager) {
    var nodes = [];
    nodesManager.requestNode = function(id) {
        // reduce number of checks
        return nodes[id] !== undefined ? nodes[id] : nodes[id] = new Node(id);
    }
} (window.nodesManager = window.nodesManager || {}));

$("#nodesList").delegate("li", "click", function() {
    // no need to wrap this in jQ just to get the id
    var node_Id = this.id.replace("node_", "");

    var newNodeName = "I am a new value";
    nodesManager.requestNode(node_Id).changeName(newNodeName);
});

如果你真的想让这块代码更有效率,除了压缩周期之外,我们还需要更深入地了解它想要实现的目标。