[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 13:39:13 -0500
The big takeaway from this is that it only takes one VM instruction to obtain the ‘len’ function from the strings metatable. That’s just something I’m going to have to accept because I don’t think I know enough for that to be explained to me, but know that, it makes perfect since that str:len() is faster given that fact.
On Aug 7, 2014, at 1:26 PM, Sean Conner <sean@conman.org> wrote:
> It was thus said that the Great Mason Mackaman once stated:
>> Thanks, but that is over my head lol.
>
> Lua code is compiled into an internal format (the Lua Virtual Machine or
> Lua VM) before it's executed. This is an important thing to remember---Lua
> code is compiled to some internal format.
>
> With that out of the way, there are four ways of getting the length of a
> string in Lua:
>
> local x = "a string"
> local y
>
> y = #x -- number 1
> y = x:len() -- number 2
> y = x.len(x) -- number 3
> y = string.len(x) -- number 4
>
> Method 1 uses one VM instruction [1] to calculate the length of the string
> (I'm ignoring the instructions that make up the assignment; they differ
> depending on if the assignment goes to a global or a local [2]) and is thus,
> the fastest method.
>
> Method 2 uses two VM instructions---one to obtain the "len" function via
> the string's metatable, and one instruction to call the function; the
> agument (x in this case) is inherent in how this works.
>
> Method 3 uses three VM instructions---one to obtain the "len" function via
> the strings metatable, one to get the argument to the function (x in this
> case) and the third to call the function.
>
> Method 4 uses four VM instructions---one to get the global "string" table
> [2], a second to obtain the "len" function from that table, the third to get
> the argument to the function, and the fourth to call the function.
>
> -spc
>
> [1] The stock Lua interpreter. The details differ for LuaJIT, but
> overall, the trend is similar.
>
> [2] Technically, to a field in a table (since "globals" are stored in a
> special table internally).
>