For more information regarding the security incident at F5, the actions we are taking to address it, and our ongoing efforts to protect our customers, click here.

Forum Discussion

BaltoStar_12467's avatar
Nov 10, 2013

simple if statements optimized to switch statements ?

Is there a performance advantage to optimizing the simplest type of if statements as switch statements ?

EXAMPLE 1 :

if { [string tolower [HTTP::path]] eq "somepage.html" } {
  pool pool-01
}

switch [string tolower [HTTP::path]] {
  "somepage.html" { pool pool-01 }
}

EXAMPLE 2 :

set path_lower [string tolower [HTTP::path]]
if { ( path_lower eq "somepage.html" ) || ( path_lower eq "anotherpage.html" ) } {
  pool mypool-01
}

switch [string tolower [HTTP::path]] {
  "somepage.html" - "anotherpage.html" { pool mypool-01 }
}

3 Replies

  • I think you can pull two rules of thumb from the above:

    • It's always better to use fewer variables if possible. Variables take up additional memory. So the following:

      set path_lower [string tolower [HTTP::path]]
      if { ( path_lower eq "somepage.html" ) || ( path_lower eq "anotherpage.html" ) } {
          pool mypool-01
      }
      

      would be better like this:

      if { ( [string tolower [HTTP::path]] eq "somepage.html" ) || ( [string tolower [HTTP::path]] eq "anotherpage.html" ) } {
          pool mypool-01
      }
      
    • A switch is generally more efficient than an if, but the difference would likely be negligible for a small set of evaluations. You'll also find that an if is usually more flexible than a switch. A switch can, at the most, evaluate wildcards with a -glob option, while an if can evaluate regular expressions and beyond. All of that said, I would still probably opt for a switch, when possible, when I have at least two or more evaluations to perform.

  • I'm surprised it's more optimal to evaluate an expression each time rather storing the result in a variable

     

    The thing is, you're not performing an evaluation with these protocol commands (ie. [HTTP::path]). The information is already stored in the state table for this request, so [HTTP::path] is itself a variable, more or less.

     

    in EXAMPLE 2 , because two comparisons are performed you'd prefer a switch over an if ?

     

    You can really go either way with 1 to 10 comparisons, but I think anything more than that just turns into confusing code. It's a matter of preference more than performance.

     

  • What I'm referring to is performing the [string tolower] operation multiple times

     

    Good point, and another good reason to use a switch since it's only done once.