[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: string buffers using string.gsub faster than table.concat
- From: David Manura <dm.lua@...>
- Date: Sat, 25 Aug 2012 23:47:08 -0400
Are there faster ways to concatenate a large number of strings in Lua
than the usually recommended table.concat approach described in PiL
2nd 11.6 "String Buffers"? The following tests show that a trick with
string.gsub can be a little faster:
-- test.lua
local mode = arg[1] or 'A'
local N = arg[2] or 1000000
local M = arg[3] or 1
local result
if mode == 'A' then
for i=1,M do
result = ((' '):rep(N):gsub('() ', function(i)
return string.char(i % 256)
end))
end
elseif mode == 'B' then
for i=1,M do
local ts = {}
for i=1,N do ts[#ts+1] = string.char(i % 256) end
result = table.concat(ts)
end
elseif mode == 'C' then
for i=1,M do
local ts = {}
for i=1,N do
ts[#ts+1] = string.char(i % 256)
while #ts >= 2 and #ts[#ts] == #ts[#ts-1] do
ts[#ts-1] = ts[#ts-1] .. ts[#ts]
ts[#ts] = nil
end
end
for i=#ts,2,-1 do
ts[i-1] = ts[i-1] .. ts[i]
ts[i] = nil
end
result = ts[1]
end
elseif mode == 'D' then
for i=1,M do
local s = ""
for i=1,N do s = s .. string.char(i % 256) end
result = s
end
end
# results for Lua 5.1, x86
$ for x in A B C D; do time test.lua $X; done
A: 0.72 0.79 0.78 s
B: 1.2 1.4 1.4 s
C: 3.0 2.6 2.6 s
D: (very long)
# for luajit 2.0-beta10
A: 0.49 0.49 0.47
B: 0.65 0.90 0.65
C: 1.7 1.9 1.8
D: (very long)