[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: string.len(str) vs str:len()
- From: Mason Mackaman <masondeanm@...>
- Date: Thu, 7 Aug 2014 08:20:28 -0500
Why is “get self ‘len’” faster than “get ‘string’, get ‘len’”?
On Aug 7, 2014, at 8:14 AM, Thiago L. <fakedme@gmail.com> wrote:
>
> On 07/08/14 10:10 AM, Mason Mackaman wrote:
>> for the following, ‘str’ is some string value.
>>
>> So I just tested the speed of str:len() and string.len(str) to see how much slower str:len() would be, but to my surprise it was actually faster. How is that possible based on what Lua says about how indexing of tables works? When you call string.len(str) Lua has to get the ‘length' key in the string table. According to gettable_event(table,key) in the reference manual, Lua will see that ‘string’ is a table, then rawget ‘length’, check to see that it’s not nil and then return it. In str:len() Lua has to check that it’s a table, that will fail so now it finds the __index key in ‘str’s metatable, sees that it’s ‘string’, checks if it’s nil, and checks if it’s a function, then finally calls string[‘length’]. How can that be faster?! It has to do a whole bunch of steps just to get to the same spot string.len(str) starts!
>>
>> While I was writing this it occurred to me that the only possible explanation was the ‘:’ operator (let me know if operator is the right word to use there). So I check str.len(str) and sure enough it was slower than string.len(str). Reading the reference manual we see that in str:len(), ‘str’ is only evaluated once, and in str.len(str), ‘str’ is evaluated twice, so it makes since why the former is faster than the later, but ‘str’ is only evaluated once in string.len(str), and you don’t have the extra steps to get ‘string.len’.
> get "string", get "len" from it, get "str", call it
> vs
> get "str", get self "len" from it, call it
> vs
> get "str", get "len" from it, get "str" (again), call it