lua-users home
lua-l archive

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




On 2019-05-05 11:03 p.m., 云风 Cloud Wu wrote:
Soni "They/Them" L. <fakedme@gmail.com> 于2019年5月5日周日 上午11:05写道:
I often write code like:

local foo = t.foo
if not foo then foo = whatever t.foo = foo end
-- use foo here

but ideally I'd like to write it like:

if not t.foo then t.foo = whatever end
local foo = t.foo

and still have the same performance (or better).

does lua do any optimizations related to this?

I have had tried to do this optimization many years ago (2012), See
the attachment for the patch, it's based on lua 5.2.1 .

I cached the last index of table hash part in Proto struct , so that
it can use it directly on next access ( for OP_GETTABUP, OP_GETTABLE,
OP_SELF) .

But I haven't seen the better performance. I guess lua's hash table is
good enough for short string keys, > 70% short string keys are on the
main index according to my experience.



Sorry, I don't understand. Is this patch meant to turn a hash operation (or hash retrieval operation in the case of Lua objects) and a comparison into just a comparison?

Ideally, I want the code:

if not t.foo then t.foo = whatever end
local foo = t.foo

to act like the following C pseudocode (including some of the unnecessary checks and branches that would be executed by the Lua VM):

void *foo;
Entry *entry = get_entry(t, "foo");
if (entry->value == NULL) {
    void *whatever;
    if (entry->key == "foo") entry->value = whatever;
    else get_entry(t, "foo")->value = whatever;
}
if (entry->key == "foo") foo = entry->value;
else foo = get_entry(t, "foo")->value;

but your code seems to use a whole other table?

Another idea would be, for short n (table hash length, 1 or 2 hash entries), it might be faster to do a linear scan of the whole hash table before trying to hash the key. But this has other issues.