简体   繁体   中英

JS switch statements: Does most-likely-case optimisation matter?

Assuming this construct

switch(foo) {
    case "foo":
        // ...
    break;
    case "bar":
        // ...
    break;
    ...
    default:
        // ...
    break;
}

or a similar conditional block (generic logical operators only), would it make sense, performance-wise, to actually put the most likely condition first?

And if so, what's the threshold where it begins to make sense vs. the "trouble" to figure out what the most likely condition will be?

This sort of micro-optimization will cause more problems than it will solve. With Javascript, it's relatively hard to assess such constructs due to the many implementation details that JS engines abstract. Profiling won't probably be very insightful either.

JS is a scripting language, not C. Make your code readable and concise — incidentally, this should always be your mantra, no matter what language you write in.

The answer is yes, it would make sense. If you knew something had a much higher percentage of being true why not put it in the first condition? I believe it's sound programming even in a scripting language.

Just because it makes sense, though, doesn't make it necessary. If it's code that isn't run frequently, it's negligible how important the order matters. However, code within a large loop with several condition statements could slow down an algorithm slightly.

The time to worry about it would be when you notice a lag. Even then, refactoring the order of conditions would probably be on the bottom of my list of things to do.

可以买到任何东西的门槛是,当您随机将其暂停几次时,您在执行该switch语句的过程中看到了它,而不是完全看到其他东西。

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