lua-users home
lua-l archive

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



> -----Original Message-----
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On
> Behalf Of Enrico Colombini
> Sent: donderdag 2 januari 2014 15:41
> To: Lua mailing list
> Subject: Re: string immutability
> 
> Thijs, here is an example:
> 
> ---------------------------------
> function GCAndShow(prompt)
>      -- (I don't remember how to force a full collection,
>      -- this hack is good enough for this example)
>      collectgarbage()
>      collectgarbage()
>      collectgarbage()
>      local kb = collectgarbage('count')
>      io.write(string.format('%s: %.1f KB\n', prompt, kb)) end
> 
> GCAndShow('initial state')
> 
> s1 = string.rep('x', 999999)
> GCAndShow('allocated a large string')
> 
> s2 = s1
> GCAndShow('assigned the same string')
> 
> s3 = string.rep('y', 999999)
> GCAndShow('allocated another, different, large string')
> 
> s4 = string.rep('x', 999998) .. 'x'
> assert(s4 == s1)
> GCAndShow('constructed a large string identical to an existing string')
> 
> s1 = nil; s2 = nil; s3=nil; s4 = nil;
> GCAndShow('deleted all strings')
> 
> ---------------------------------
> 
> Lua 5.1 prints:
> 
> initial state: 20.6 KB
> allocated a large string: 1012.4 KB
> assigned the same string: 997.4 KB
> allocated another, different, large string: 1989.0 KB constructed a large
> string identical to an existing string: 1989.0 KB deleted all strings: 20.8
> KB
> 
> ---------------------------------
> 
> Lua 5.2 prints:
> 
> initial state: 15.0 KB
> allocated a large string: 991.6 KB
> assigned the same string: 991.6 KB
> allocated another, different, large string: 1968.2 KB constructed a large
> string identical to an existing string: 1968.2 KB deleted all strings: 15.0
> KB
> 
> ---------------------------------
> 
> As you can see, in both cases a string built by concatenation does not take
> up extra memory if it is identical to an existing one. Change the final 'x'
> of the s4 expression to an 'y' (also comment out the assert) and you will
> see the difference.
> 
> --
>    Enrico

Thx. Very clear!

Thijs