简体   繁体   中英

switch vs object lookup performance (since jsperf is down)

The way I see it, for certain situations, there are two ways to do something if some value equals something: a switch or an object lookup.

Using a switch:

 var value = ["Hello", "hi", "bYe", "die"][Math.floor(Math.random() * (4))]; switch (value.toLowerCase()) { case "hello": alert(value + "\n\n" + "hi"); break; case "hi": alert(value + "\n\n" + "hello"); break; case "bye": alert(value + "\n\n" + "no"); break; case "die": alert(value + "\n\n" + "you shot me"); break; }

Using an object lookup:

 var value = ["Hello", "hi", "bYe", "die"][Math.floor(Math.random() * (4))]; var LOOKUP = { "hello": function(v) { alert(v + "\n\n" + "hi"); }, "hi": function(v) { alert(v + "\n\n" + "hello"); }, "bye": function(v) { alert(v + "\n\n" + "no"); }, "die": function(v) { alert(v + "\n\n" + "you shot me"); }, }; LOOKUP[value.toLowerCase()](value);

I am wondering which would have better performance?

And would there be any unobvious issues/gotchas with either approach?

ORIGINAL ANSWER: A Lookup Table is much, much faster.

UPDATED ANSWER 2020: The two methods perform pretty much the same in modern browsers, with the switch statement being 20-30% faster than the lookup table.

I had the same question a while back. If jsperf ever gets revived, this is the link. https://jsperf.com/if-switch-lookup-table/10

Edit: Working benchmark https://jsben.ch/JYZLQ

Its a trade-off between time complexity and space complexity, imagine a switch with 10000 cases, so you would create an object with 10000 keys, and the entire object would have to be loaded in a memory/cache for lookup where as for switch-case it will be jumping from one instruction to another based upon the condition,

I personally prefer object-key lookup over switch-case as its more maintainable code and its extensible design pattern as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM