|
Hi all,I've searched the archives but can't find a post regarding this question.
I've been timing table accesses under LuaJIT using various key types in a very simple tight loop. Positive integers are the fastest (of course), while negative integers, tables, and functions used as indices are approximately 33% slower. That's not bad, given that we're using the hashed storage for the table in these cases.
But when I test using strings as table keys they time out as over 100% slower, meaning they take twice as long to execute. I've got the code structured to avoid any string operations, so those aren't a part of the timing.
This was very surprising to me, because my assumption was that any key would be used in essentially the same way for a lookup. Does anyone know why string keys are so much slower? And does this mean that for maximum performance we'd be better off always using "tab[index]" accesses instead of "tab.name" accesses?
Inquiring minds want to know, :-) -gary The test code:
local count = 10000000 local size = 100000 local h = {} local hi = {} local t = {} local ti = {} for i = 1, size do local key = -i -- change the key type we're testing right here. -- local key = ""..i -- as string -- local key = {} -- as table -- local key = function () end -- as function h[key] = i hi[i] = key t[i] = i ti[i] = i end local random = math.random local time = os.clock() local acc = 0 for i = 1, count do acc = acc + t[ ti[random(size)] ] end printf( "index time is %0.2f\n", os.clock() - time ) time = os.clock() acc = 0 for i = 1, count do acc = acc + h[ hi[random(size)] ] end printf( "hash time is %0.2f\n", os.clock() - time )