LoginSignup
12
10

More than 5 years have passed since last update.

luaのforとwhileのパフォーマンス差

Posted at

luaはループの書き方によって実行速度に差が出るっぽくて、forが圧倒的に速い。
前のエントリを書いててたまたま気づいたんだけど、面白いのでメモ。

ベンチマーク

純粋に繰り返しのみを行うコードで、forとwhileのどちらを使うかだけを変えている。

while.lua
local start = os.clock()
local COUNT = 1000000000 

local i = 0
while i < COUNT do
    i = i + 1
end

print( os.clock() - start )
for.lua
local start = os.clock()
local COUNT = 1000000000 

for i=0, COUNT do
end

print( os.clock() - start )

結果

forが3倍ほど高速であることがわかる。
# 最適化によってループが省略されている可能性も疑ったが、実用コードに入れても絶対差としては同程度だった。

for.lua while.lua
1 5.25 17.28
2 5.34 17.70
3 5.32 17.39
12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10