lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Aug 19, 2009 at 11:19 PM, Michael
Newberry<mnewberry@mirametrics.com> wrote:
> Then it would be nice to add that detail! PIL goes into detail about the
> performance penalty of doing great numbers of concatenations.
>

I think the key here is that concatentation in a loop in Lua is to be
discouraged:

for i = 1, 100 do
   a = a .. " "
end

This is because when you assign a.." " to a, the old string that was
in a is discarded. So on each loop iteration you are making a new
(longer string) and throwing away the old shorter string. This results
in a flurry of allocation/deallocation, which is bad for performance.

" ".." ".." ".." " (up to a hundred) however would only create one
string, and do one (giant) concatenation.

string.rep() does exactly the same as the long sequence above. It
allocates as much memory as is needed in sequence, it doesn't keep
throwing away old strings. Then it concatenates it all into a single
Lua string when it is done.

So PiL is right, don't concatentate in a loop, but the length of a
concatenation is not a(s much a) concern.

Matthew