Is the order of labels in a select case statement important?

Viewed 80

I was wondering about the performance of Fortran code as the number of list items in a case statement increases. I guess there's an upper bound set by the compiler for the number of list items, but for the applications I'm typically using case statements for, the occurrence of the list items is non-random, and so is the positional order important in the list. Specifically, will code be faster with the more frequently occurring items benefit from being ordered earlier in the list?

So will

case ('common case', 'rare case', 'very rare case')

run faster than

case ('very rare case', 'rare case', 'common case')

1 Answers

The order of value ranges in a selector, and indeed the order of selectors within the case construct as a whole, does not define an order of evaluation of comparison.

In that sense, no, the order of case(a,b,c) against case(c,b,a) does not affect the performance of your code.

A compiler is free to compare selectors and value ranges within a selector against the case expression in any order or even some at the same time or not at all (in the final case if it knows the constant expression can never match), regardless of how written.

If you write case(common, rare, inexplicable) the compiler can see that as case(prohibitively_expensive_comparison, compare_if_i_must, trivial_to_check) and decide to compare in a corresponding order. Or the compiler may use profiling-driven optimization.

That said, if the compiler decides to compare in a linear way, sequentially, each value range as written, yes, you may see a (tiny) performance gain by ordering in terms of frequency.

To ensure a compiler may evaluate as it chooses, you must write code in such a way that there can ever be only one match.

In conclusion: test and profile your code. But be nice to readers and code reviewers who will struggle to understand your code much more than your compiler will.

Related