Forum Discussion
Heisenberg_1452
Feb 28, 2014Historic F5 Account
string equal/compare/match vs. switch
All,
Very new to iRules. Wondering if anyone knows what is more efficient:
switch $foo {
"bar" {...}
"bar1" {...}
"bar2" {...}
default {...}
}
vs.
if {string e...
Kevin_Stewart
Employee
Feb 28, 2014Here's a fun way to test the efficiency of each command. Create a text file in the shell:
!/usr/bin/tclsh
proc random { } {
set mylist [list "bar" "bar1" "bar2" "blah"]
set index [expr int(rand() * 4)]
return [lindex $mylist $index]
}
set foo [random]
set timer [time {
switch $foo {
"bar" { set test "bar" }
"bar1" { set test "bar1" }
"bar2" { set test "bar2" }
default {set test "def" }
}
} 1000000]
puts "switch: $timer"
set timer [time {
if { [string equal $foo "bar"] } {
set test "bar"
} elseif { [string equal $foo "bar1"] } {
set test "bar1"
} elseif { [string equal $foo "bar2"] } {
set test "bar2"
} else {
set test "def"
}
} 1000000]
puts "str equal: $timer"
set timer [time {
if { [string compare $foo "bar"] } {
set test "bar"
} elseif { [string compare $foo "bar1"] } {
set test "bar1"
} elseif { [string compare $foo "bar2"] } {
set test "bar2"
} else {
set test "def"
}
} 1000000]
puts "compare: $timer"
set time [time {
if { [string match $foo "bar"] } {
set test "bar"
} elseif { [string match $foo "bar1"] } {
set test "bar1"
} elseif { [string match $foo "bar2"] } {
set test "bar2"
} else {
set test "def"
}
} 1000000]
puts "match: $timer"
set timer [time {
if { $foo == "bar" } {
set test "bar"
} elseif { $foo == "bar1" } {
set test "bar1"
} elseif { $foo == "bar2" } {
set test "bar2"
} else {
set test "def"
}
} 1000000]
puts "equals: $timer"
Then chmod the file and run in it. It may be an anomaly, but I almost consistently get lower times for match and compare, followed closely by switch.
Help guide the future of your DevCentral Community!
What tools do you use to collaborate? (1min - anonymous)Recent Discussions
Related Content
DevCentral Quicklinks
* Getting Started on DevCentral
* Community Guidelines
* Community Terms of Use / EULA
* Community Ranking Explained
* Community Resources
* Contact the DevCentral Team
* Update MFA on account.f5.com
Discover DevCentral Connects