2010-03-10 647 views
1

我正在写一个函数add_event如下面所示:此javascript语句是否影响性能?

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,这就是我问这个问题的原因。万分感谢。

回答

3

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

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

一个字符串并不一定是'String'的实例(不是'string'!)。 “typeof”是正确的选择。 – Gumbo 2010-03-10 09:10:20

+0

@Gumbo变了。 – Amarghosh 2010-03-10 09:22:38

2

否。大多数JavaScript解释器不会受其影响。那些做的最多只会影响几微秒。

在这种情况下,您应该重点关注如何让您的代码具有可读性和可维护性。试图通过非常简单的操作来压缩性能只会浪费时间,并且可能会让代码难以维护。

如果您觉得您的JavaScript代码表现不佳,可以使用各种工具和策略来查找和解决问题。以下堆栈溢出问题有更多的话题:What is the best way to profile javascript execution?

祝你好运!