The following question came in regarding optimization of iRules:

Do you know whether if-elseif (nested if) or switch (case) is more efficient using the TCL interpreter on v9 ?

In his usually verbose self, unRuleY responded as follows:

You could attempt to measure it now that you have both versions working. You can enable rule timing by using the "timing on" command at the top of the rule before the when clause
timing on
when HTTP_REQUEST {
   ...
}

(Note: don't leave this turned on indefinitely as it does have a small impact on performance). This will cause cycle counts to be displayed when viewing rule statistics (ie: bigpipe rule show all). You could run a couple thousand iterations to get a decent average for each of the methods.

Another factor that will influence your results is how often the first vs. second vs. last comparison matches. You can influence the performance by moving the most matched string first and the least matched last.

However, there are a couple of factors that I could argue would make one method faster over the other, but I can't make a good guess as to which factor is going to be most influential. Empirical data would be best way to determine this. Here are the two most influential arguments for each method:

In the if-elseif-else method, the "starts_with" operator is an operator designed specifically to match only the beginning of the string, whereas the switch command must do a string pattern match. Pattern matching is going to cost more cpu.

In the switch command method, the switch command does a pre-compiled iteration over the provided list of patterns as opposed to the byte-code interpreted branch-test-branch approach of the if-elseif-else method. Though the Tcl byte-code is very fast, it's never going to be as fast as native machine language.

Ultimately, both of these methods should yield very good performance and I personally would probably use the method that is easiest to maintain in this case.

Click here for the original thread.

-Joe

 

[Listening to: Highway Chile - Jimi Hendrix Experience - The Ultimate Experience (03:30)]