Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - Performance of if-else, switch or map based conditioning

I was wondering about the performances of the following implementations of conditional structs in javascript.

Method 1:

 if(id==="camelCase"){
    window.location.href = "http://www.thecamelcase.com";
}else if (id==="jsFiddle"){
    window.location.href = "http://jsfiddle.net/";
}else if (id==="cricInfo"){
    window.location.href = "http://cricinfo.com/";
}else if (id==="apple"){
    window.location.href = "http://apple.com/";
}else if (id==="yahoo"){
    window.location.href = "http://yahoo.com/";
}           

Method 2:

switch (id) {
case 'camelCase':
    window.location.href = "http://www.thecamelcase.com";
    break;
case 'jsFiddle':
    window.location.href = "http://www.jsfiddle.net";
    break;
case 'cricInfo':
    window.location.href = "http://www.cricinfo.com";
    break;
case 'apple':
    window.location.href = "http://www.apple.com";
    break;
case 'yahoo':
    window.location.href = "http://www.yahoo.com";
    break;

}

Method 3

var hrefMap = {
camelCase : "http://www.thecamelcase.com",
jsFiddle: "http://www.jsfiddle.net",
cricInfo: "http://www.cricinfo.com",
apple: "http://www.apple.com",
yahoo: "http://www.yahoo.com"
};
window.location.href = hrefMap[id];

Method 4

window.location.href = {
    camelCase : "http://www.thecamelcase.com",
    jsFiddle: "http://www.jsfiddle.net",
    cricInfo: "http://www.cricinfo.com",
    apple: "http://www.apple.com",
    yahoo: "http://www.yahoo.com"
}[id];

Probably Method 3 and 4 might have almost the same performance but just posting to confirm.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to this JSBen.ch test, the switch setup is the fastest out of the provided methods (Firefox 8.0 and Chromium 15).

Methods 3 and 4 are slightly less fast, but it's hardly noticeable. Clearly, the if-elseif method is significantly slower (FireFox 8.0).

The same test in Chromium 15 does not show significant differences in performance between these methods. In fact, the if-elseif method seems to be the fastest method in Chrome.

Update

I have run the test cases again, with 10 additional entries. The hrefmap (methods 3 and 4) show a better performance.

If you want to implement the compare method in a function, method 3 would definitely win: Store the map in a variable, and refer to this variable at a later point, instead of reconstructing it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...