1

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?

vzwick
  • 11,008
  • 5
  • 43
  • 63

3 Answers3

3

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
David Titarenco
  • 32,662
  • 13
  • 66
  • 111
  • Can I infer from your answer that there would be a considerable performance gain in C/compiled languages by and large? – vzwick Oct 26 '11 at 01:52
  • @vzwick, no you cannot. If the language doesn't specify something (i.e. how switch statements should be optimized -- which it does not), it's completely up to the compiler. Even though VC++ and gcc may be quite clever when optimizing such things, if Jimmy makes his own compiler, the same optimizations may not be implemented. Coding with such optimizations in mind is sometimes detrimental as it hinders binary portability or readability of source code. – David Titarenco Oct 27 '11 at 01:04
1

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.

MillsJROSS
  • 1,239
  • 7
  • 9
1

The threshold where it would buy you anything is if, when you randomly pause it several times, you see it in the process of executing that switch statement, as opposed to something else entirely.

Community
  • 1
  • 1
Mike Dunlavey
  • 40,059
  • 14
  • 91
  • 135