Which is faster of two case or if? [closed]
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; done4550real 0m22.154suser 0m21.750ssys 0m0.380suser@machine:~$ time for i in {1..1000000}; do case "$i" in "45") echo $i;; "50") echo $i;; esac; done4550real 0m10.286suser 0m10.230ssys 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; done45506000real 0m32.602suser 0m32.070ssys 0m0.510suser@machine:~$ time for i in {1..1000000}; do case "$i" in "45") echo $i;; "50") echo $i;; "6000") echo $i;; esac; done45506000real 0m13.553suser 0m13.520ssys 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; done45506000real 0m15.127suser 0m15.090ssys 0m0.010suser@machine:~$ time for i in {1..1000000}; do case $i in 45) echo $i;; 50) echo $i;; 6000) echo $i;; esac; done45506000real 0m9.966suser 0m9.940ssys 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; donereal 0m5.095suser 0m5.070ssys 0m0.010s