I am using Nginx + Lua (OpenResty, LuaJIT), and I did some performance tests on various loops.
local ngx_log = ngx.log
-- https://openresty-reference.readthedocs.io/en/latest/Lua_Nginx_API/#nginx-log-level-constants
local ngx_LOG_TYPE = ngx.STDERR
local N=1e8
t0=os.clock()
a = 0
while a < N do
a = a + 1
end
t1=os.clock()-t0
ngx_log(ngx_LOG_TYPE,"While Global " .. t1 .. " " .. math.floor(t1/t1*100+0.5))
t0=os.clock()
local a = 0
while a < N do
a = a + 1
end
t2=os.clock()-t0
ngx_log(ngx_LOG_TYPE,"While Local " .. t2 .. " " .. math.floor(t1/t2*100+0.5))
t0=os.clock()
b = 0
for i=1,N do
b = b + 1
end
t3=os.clock()-t0
ngx_log(ngx_LOG_TYPE,"For Global " .. t3 .. " " .. math.floor(t1/t3*100+0.5))
t0=os.clock()
local b = 0
for i=1,N do
b = b + 1
end
t4=os.clock()-t0
ngx_log(ngx_LOG_TYPE,"For Local " .. t4 .. " " .. math.floor(t1/t4*100+0.5))
Here is the output:
[lua] test.lua:14: While Global 0.048999999999999 100, client: 127.0.0.1, server: localhost, request: "GET /test.lua HTTP/1.1", host: "localhost"
[lua] test.lua:22: While Local 0.030000000000001 163, client: 127.0.0.1, server: localhost, request: "GET /test.lua HTTP/1.1", host: "localhost"
[lua] test.lua:30: For Global 0.057000000000002 86, client: 127.0.0.1, server: localhost, request: "GET /test.lua HTTP/1.1", host: "localhost"
[lua] test.lua:38: For Local 0.036000000000001 136, client: 127.0.0.1, server: localhost, request: "GET /test.lua HTTP/1.1", host: "localhost"
They execute very fast, but the while loops are a tiny fraction faster than the for loops.
Should I change all my code to use while loops instead of for loops?