test vs. let


0. Contents

1.Concept
2.Test Script
3.Run Test
4.Summary


1. Concept

test はファイル形式のチェックや値の比較を行うコマンドで
let は算術式を評価する bash の builtin コマンドである。
両者の数字の比較を行う場合の処理速度を比較してみた。


2. Test Script

比較の為のスクリプトを作成した。
ソースは以下の通り。

Script1
#! /usr/bin/env bash
declare -i a=0 b=10000

test1(){
  local a="$a" b="$b"
  while [ $a -lt $b ] ; do
    (( a++ ))
  done
}

test2(){
  local a="$a" b="$b"
  while (( a < b )) ; do
    (( a++ ))
  done
}

time test1
time test2
exit

Script2
#! /usr/bin/env bash
function test(){
  [ "$1" -gt 0 ]  && echo 'test1 OK'
  [ "$1" = 1 ]    && echo 'test2 OK'
  (( "$1" > 0 ))  && echo 'test3 OK'
  (( "$1" == 1 )) && echo 'test4 OK'
}

test 1
test 2
test '2-1'
exit


3. Run Test

上記のスクリプトの実行結果。

Script1
test1
real    0m0.766s
user    0m0.750s
sys     0m0.010s

test2
real    0m0.497s
user    0m0.490s
sys     0m0.000s

Script2
"1" の場合
test1 OK
test2 OK
test3 OK
test4 OK

"2" の場合
test1 OK
test3 OK

"2-1" の場合
[: 2-1: integer expression expected
test3 OK
test4 OK


4. Summary

わずかではあるが let の方が速いという結果が出た。
ただし、let は算術結果を評価するので変数の中身によっては
期待通りの結果が返るとは限らないので注意。