For our third installment of the iRules Optimization 101 series, we're going to cover loop control structures and how to gain efficiency therein. Other articles in the series:

One of the things that makes iRules so powerful is the fact that it is effectively a full scripting language at your fingertips with which you can inspect and modify traffic in real time. As with any scripting language, TCL (which iRules is based on) makes use of different loop control structures to perform different tasks. These are usually used in more advanced iRules, but we'll take a look at a couple of simple examples for ease of reading.

In the below examples we're going to be looking at a relatively simple situation. In both we're going to be taking a list of strings, domain names in this case, and cycling through that list one at a time, performing some given tasks on each item in the list.

Section One: for loops

In the first example, we use a "for" loop. This is one of the most common loop structures around, and is used in many, many languages. While this example certainly functions, you'll notice there are many steps required to get to the point of actually performing the actions based on the data in question. While this is one of the preferred loops in many languages as it is relatively robust and functional, and the difference in overhead is less important, this is a bit expensive for iRules, unless there is an actual need.

when HTTP_REQUEST {
  set domains {bob.com ted.com domain.com}

  set countDomains [llength $domains]
  for {set i 0} { $i < $countDomains } {incr i} {
    set domain [lindex $domains $i]
    # This is slower
  }
}

Section Two: foreach

This next example is logically similar. It accomplishes the same task in this case, and does so with less overhead. See how we have less variables to set, and less functions to perform for each loop iteration? While foreach is sometimes thought of as slightly less powerful or flexible than a for loop, it is markedly more efficient. As such, in cases where it will accomplish the task at hand, it is by far the preferred structure.

when HTTP_REQUEST {  
  set domains {bob.com ted.com domain.com}
  foreach domain $domains {
    # This is faster, and more elegant
  }
}

Again, while this may seem like a simple concept, it is just an introduction into the ways of thinking about iRule Optimization. This same thought process can apply in many ways. Are those extra variables really needed? Do you really need a regular expression, or will a different function suffice? Do you actually need to process every response, or can you process only some? This type of thinking is imperative to writing the fastest, most efficient iRules possible.

Get the Flash Player to see this player.