【问题标题】:Does this javascript statement affects performance?这个 javascript 语句会影响性能吗?
【发布时间】:2010-03-10 08:57:05
【问题描述】:

我正在编写一个函数 add_event,如下所示:

function add_event(o, event_type, callback, capture){
    o = typeof o === "string" ? document.getElementById(o) : o;
    if(document.addEventListener){
        add_event = function(o, event_type, callback, capture){
            o = typeof o === "string" ? document.getElementById(o) : o;
            o.addEventListener(event_type, callback, capture);
        }
    }else if(document.attachEvent){
        add_event = function(o, event_type, callback, capture){
            o = typeof o === "string" ? document.getElementById(o) : o;
            o.attachEvent("on" + event_type, callback);
        }
    }
    add_event(o, event_type, callback, capture);
}

现在我的问题是声明是否

o = typeof o === "string" ? document.getElementById(o) : o;

影响这个程序的性能?如果你传递一个 HTML 元素而不是一个 id,你实际上会执行语句 o = o,这就是我问这个问题的原因。非常感谢。

【问题讨论】:

    标签: javascript performance variable-assignment


    【解决方案1】:

    js 解释器可能会优化它。即使没有,效果也不会很明显。如果您真的担心,请将其更改为:

    if(typeof o === "string")
      o = document.getElementById(o);
    

    【讨论】:

    • 字符串绝不是String 的实例(不是string!)。 typeof 是正确的方法。
    【解决方案2】:

    没有。大多数 javascript 解释器的性能不会受此影响。这样做的人最多只会受到几微秒的影响。

    在这种情况下,您应该专注于使您的代码具有可读性和可维护性。试图从非常简单的操作中榨取性能只会浪费时间,并且可能会使您的代码更难维护。

    如果您觉得您的 javascript 代码性能不佳,您可以使用多种工具和策略来查找和解决问题。以下堆栈溢出问题有更多关于该主题的内容:What is the best way to profile javascript execution?

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2011-04-11
      • 2013-06-20
      • 1970-01-01
      • 2015-04-23
      相关资源
      最近更新 更多