1

I'm writing a function add_event as the following shows:

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);
}

Now my question is whether the statement

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

affects the performance of this program? If you pass an HTML element instead of an id, you infact executes the statement o = o, this is the reason why I ask this question. Great Thanks.

asked Mar 10, 2010 at 8:57

2 Answers 2

3

Chances are that the js interpreter will optimize it out. Even if it doesn't, the effect won't be noticeable. And if you're really concerned, change it to:

if(typeof o === "string")
 o = document.getElementById(o);
answered Mar 10, 2010 at 9:03
Sign up to request clarification or add additional context in comments.

1 Comment

A string is not by all means an instance of String (not string!). typeof is the right way to go.
2

No. Most javascript interpreters will not have their performance affected by this. Those that do will have it affected by a few microseconds at most.

In cases like this you should focus on making your code readable and maintainable. Trying to squeeze performance out of very simple operations is only going to waste time and possibly make your code harder to maintain.

If you feel that your javascript code is performing poorly, there are a variety of tools and strategies you can use to find and fix the problem. The following stack overflow question has more on the topic: What is the best way to profile javascript execution?

Good luck!

answered Mar 10, 2010 at 9:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.