Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster of two case or if? [closed]

I have to make a "very" light script which would take in options from user and call in functions within the script to perform some tasks.

Now I can us both IF and CASE options, but I want to know which among both will be lighter. CASE obviously looks less complex when I put it in script, does it make my script lighter as well in terms of computation/CPU usage/memory usage or IF is better ?

The script will have around 10-15 input options to select from, the no. of option for choosing might increase in future, if new functionality gets added.

Note:- It's for usage in bash running on Solaris 10/RHEL 6

like image 337
Marcos Avatar asked Sep 15 '25 23:09

Marcos


1 Answers

Although I agree with other comments that bash is itself slow, I just executed some tests here to check the difference. Platform is Ubuntu 10.10 on a slow machine. No other processes running in parallel.

CASE is taking less than half the time, which is quite surprising:

user@machine:~$ time for i in {1..1000000}; do if [ "$i" == "45"  ]; then echo $i; elif [ "$i" == "50" ]; then echo $i; fi; done
45
50

real    0m22.154s
user    0m21.750s
sys     0m0.380s

user@machine:~$ time for i in {1..1000000}; do case "$i" in "45") echo $i;; "50") echo $i;; esac; done
45
50

real    0m10.286s
user    0m10.230s
sys     0m0.040s

Repeating the experiment, but adding a third comparison:

user@machine:~$ time for i in {1..1000000}; do if [ "$i" == "45"  ]; then echo $i; elif [ "$i" == "50" ]; then echo $i; elif [ "$i" == "6000" ]; then echo $i; fi; done
45
50
6000

real    0m32.602s
user    0m32.070s
sys     0m0.510s

user@machine:~$ time for i in {1..1000000}; do case "$i" in "45") echo $i;; "50") echo $i;; "6000") echo $i;; esac; done
45
50
6000

real    0m13.553s
user    0m13.520s
sys     0m0.010s

It looks like IF simply repeats a comparison 3 times while CASE makes a single comparison, which could explain why CASE is almost constant while IF seems to take a time that is proportional to the number of comparisons.

Now checking the suggested [[ $i == 45 ]]:

user@machine:~$ time for i in {1..1000000}; do if [[ $i == 45  ]]; then echo $i; elif [[ $i == 50 ]]; then echo $i; elif [[ $i == 6000 ]]; then echo $i; fi; done
45
50
6000

real    0m15.127s
user    0m15.090s
sys     0m0.010s

user@machine:~$ time for i in {1..1000000}; do case $i in 45) echo $i;; 50) echo $i;; 6000) echo $i;; esac; done
45
50
6000

real    0m9.966s
user    0m9.940s
sys     0m0.010s

Again, CASE is faster, but not that faster.

To try to determine the time wasted on the FOR-LOOP itself, let's try to run almost nothing:

user@machine:~$ time for i in {1..1000000}; do x=0; done

real    0m5.095s
user    0m5.070s
sys     0m0.010s
like image 111
Akira Avatar answered Sep 18 '25 16:09

Akira