|
|
||
|
> I think you want to test for empty string, that is not the same as nil.
> Try this one:
>
> for count = 1, math.huge do
> local line = io.read()
> if #line == 0 then break end
> io.write(string.format("%6d ", count), line, "\n")
> end
A little note: this is kind of slower way to check if string is empty.
Fastest would be to compare with empty string constant:
for count = 1, math.huge do
local line = io.read()
if line == "" then break end
io.write(string.format("%6d ", count), line, "\n")
end
Please note that the difference is quite small though (note 10^9 iterations).
Benchmarking results follow.
Legend: "empty" is test with line being empty string, "nonempty" --
with non-empty string. The "constant" is `line == ""`, "size" is
`#line == 0` and "upvalue" is comparison with upvalue, containing
empty string.
$ time lua estrbench.lua empty_constant 1000000000
127.46 real 126.46 user 0.36 sys
$ time lua estrbench.lua empty_upvalue 1000000000
134.89 real 133.78 user 0.42 sys
$ time lua estrbench.lua empty_size 1000000000
141.92 real 140.77 user 0.42 sys
$ time lua estrbench.lua nonempty_constant 1000000000
123.05 real 122.07 user 0.34 sys
$ time lua estrbench.lua nonempty_size 1000000000
139.43 real 138.26 user 0.41 sys
$ time lua estrbench.lua nonempty_upvalue 1000000000
164.73 real 163.36 user 0.48 sys
LuaJIT improves speed greatly
$ time luajit -O estrbench.lua empty_constant 1000000000
18.22 real 17.90 user 0.08 sys
$ time luajit -O estrbench.lua empty_size 1000000000
25.30 real 25.08 user 0.07 sys
$ time luajit -O estrbench.lua empty_upvalue 1000000000
27.81 real 27.57 user 0.08 sys
$ time luajit -O estrbench.lua nonempty_constant 1000000000
17.74 real 17.58 user 0.06 sys
$ time luajit -O estrbench.lua nonempty_upvalue 1000000000
28.76 real 28.33 user 0.12 sys
$ time luajit -O estrbench.lua nonempty_size 1000000000
25.53 real 25.10 user 0.10 sys
Benchmark attached, run it as
$ KBENCH_SCRIPT=estrbench.lua KBENCH_NUM_ITER=1000000000 ./kbench.sh
Sorry if my silly benchmarks are too nagging.
Alexander.
Attachment:
kbench.sh
Description: Bourne shell script
Attachment:
estrbench.lua
Description: Binary data