Discussion:
[Help-bash] Is `while :` preferred over `while true`?
Peng Yu
2018-03-03 14:20:02 UTC
Permalink
Hi,

When I run the following command, it seems that `while :` is not
always faster than `while true`. But my understanding is that `while
true` calls the bash internal command `true` but `while :` does not
call anything. So I think `while :` should be always better in terms
of runtime. Is it so? Thanks.

$ ./main.sh
time ./script_true.sh

real 0m1.679s
user 0m1.628s
sys 0m0.038s
time ./script_colon.sh

real 0m1.719s
user 0m1.632s
sys 0m0.055s


==> main.sh <==
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
time ./script_true.sh
time ./script_colon.sh


==> script_colon.sh <==
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

i=0
while :
do
if ((i>100000))
then
break
fi
((++i))
done


==> script_true.sh <==
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

i=0
while true
do
if ((i>100000))
then
break
fi
((++i))
done
--
Regards,
Peng
Chet Ramey
2018-03-04 21:53:59 UTC
Permalink
Post by Peng Yu
Hi,
When I run the following command, it seems that `while :` is not
always faster than `while true`. But my understanding is that `while
true` calls the bash internal command `true` but `while :` does not
call anything. So I think `while :` should be always better in terms
of runtime. Is it so? Thanks.
Why would you think they are different? They are both builtins that do
the exact same thing. In fact, they're implemented using the same function.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU ***@case.edu http://tiswww.cwru.edu/~chet/
Loading...