Ulysses
Ulysses

Reputation: 6015

What is faster to execute - expr or if

I am looking at the possibility of optimizing the execution of some of my existing code using ternary operators in single command containing if and else blocks.

Is the ternary operator approach faster than the traditional if / else e.g which is faster to execute of the following:

First:

expr {[info exists arr($var)]? [return $_timeouts($var)] : [puts "No key $var has been set"]}

Second:

if {[info exists arr($var)]} { 
    [return $_timeouts($var)]
} else {
    puts "No key $var has been set"
}

Notice that the entire expr in the ternary operator approach (First) is contained in a single {} block and I am hoping this will be faster to execute than the Second approach.

Thanks

Upvotes: 0

Views: 138

Answers (1)

Brad Lanam
Brad Lanam

Reputation: 5723

You can use the built-in time command to test your question.

I changed 'puts' to a different 'return' statement so that the speed of a variable that exists in the array could be directly compared to the speed of a variable that does not exist in the array.

variable arr

proc test1 { var } {
  variable arr

  expr {[info exists arr($var)] ? [return $arr($var)] : [return -1]}
}

proc test2 { var } {
  variable arr

  if { [info exists arr($var)] } {
    return $arr($var)
  } else {
    return -1
  }
}

proc init { } {
  variable arr

  # fill arr with stuff...
  for {set i 0} {$i < 10000} {incr i} {
    set arr($i) $i
  }
}

init
puts [time {test1 9000} 10000]
puts [time {test1 15000} 10000]
puts [time {test2 9000} 10000]
puts [time {test2 15000} 10000]

The results on my machine:

bll-tecra:bll$ tclsh t.tcl
1.3121 microseconds per iteration
1.0267 microseconds per iteration
1.1399 microseconds per iteration
0.9029 microseconds per iteration

So using expr is a bit slower. In this case, the more readable code is definitely a win.

The speed difference is pretty small. If this small of a difference is affecting your program, I also recommend trying this code with a dictionary rather than a array and check the speed differences.

Upvotes: 4

Related Questions