String referencing

431 views Asked by At

In my code I need to keep track of certain value (a string, always...) in a local. I'd like to know whether the run time will re-create or examinate this string after putting it in a local, on the official Lua 5.3 implementations. Any ideas? In this lua.org document I've at least heard the Lua implementation does string internalization (keep a single copy of any string).

I'm restarting my code, so I've done insignificant things so far. An example of what I might do per function is:

local src = l[1]

-- `src` would hold a string
1

There are 1 answers

2
iehrlich On BEST ANSWER

If the strings are interned or not is actually not a concern - string interning is simply a mechanism to speed up string comparisons and (probably) spare some memory at the expense of CPU needed to create a string.

What matters is the fact that strings in lua are what is usually called reference types. This is, runtime values only hold and share references to the strings, and assigning a string to a runtime value is simply copying a pointer and setting up proper tag for this value.

Another thing your code does, is it allows you to avoid multiple hash lookups during the execution of your function. For example,

local a       = tbl['mykey']
-- ...
local other_a = tbl['mykey']

will result in two hash lookups, while

local cached_a = tbl['mykey']
-- ...
local a = cached_a
-- ...
local other_a = cached_a

will reduce it to one lookup. But yet again, this is usually not a big deal for integer keys. But sometimes even integer keys trigger hash lookups, even if they are small. Also, it's implementation dependent. Lua is very simple.