Here's an approach that uses a table, but the table does not get very big. To concatenate 'n' string it performs O(n log n) concatenations
An implementation in 'C' would of course be faster, but appending 2 million characters one at a time took about 0.4 seconds on my laptop, so it's not horrible.
I believe Lua does something similar internally, as does the Java StringBuilder class.
Ge'
local buffer_class = {}
function buffer_class:append(a)
if #a > 0 then
local size = #self
while size > 0 and 2*#a > #self[size] do
a, self[size] = self[size] .. a, nil
size = size - 1
end
self[size+1] = a
end
end
function buffer_class:get()
return table.concat(self)
end
local buffer_mt = { __index = buffer_class }
local function new_buffer()
return setmetatable({}, buffer_mt)
end
local b = new_buffer()
for i = 1, 1000000 do
b:append("x")
b:append("y")
end
local s = b:get()
print("# of slots:", #b, #s)