lua-users home
lua-l archive

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


On 10/18/2012 03:46 PM, Javier Guerra Giraldez wrote:
On Thu, Oct 18, 2012 at 12:14 PM, Elias Barrionovo
<elias.tandel@gmail.com> wrote:
I have no idea about lua/luajit internals but i don't use `:` because i
imagine that interpreter has to additionally follow metatable on every call.

I'd guess that in this case str:gmatch triggers only one metatable
lookup, since gmatch will return an iterator that will be called
throughout the loop.

right, the expression in the generic for is evaluated only once.

besides, a metatable indirection is far, far less expensive than most
processing done in any but the most trivial loop body (and is
optimized away by LuaJIT).

Besides which wouldn't there be, if not a metatable lookup, at least a table lookup, to retrieve the value of string.gmatch in Luiz's original example? I did a simple experiment which seems to indicate that it requires fewer VM instructions (if not less processing) to use the string's metatable, assuming that one has not cached the value of string.gmatch in an upvalue or such.

-- David

file: test-str-mtab.lua
function gmatch1( str ) return string.gmatch( str, "foo" ); end
function gmatch2( str ) return str:gmatch( "foo" ); end

luac -l test-str-mtab.lua

main <test-str-mtab.lua:0,0> (5 instructions at 0x1ad43f0)
0+ params, 2 slots, 1 upvalue, 0 locals, 2 constants, 2 functions
	1	[3]	CLOSURE  	0 0	; 0x1ad4600
	2	[1]	SETTABUP 	0 -1 0	; _ENV "gmatch1"
	3	[7]	CLOSURE  	0 1	; 0x1ad4b90
	4	[5]	SETTABUP 	0 -2 0	; _ENV "gmatch2"
	5	[7]	RETURN   	0 1

function <test-str-mtab.lua:1,3> (7 instructions at 0x1ad4600)
1 param, 4 slots, 1 upvalue, 1 local, 3 constants, 0 functions
	1	[2]	GETTABUP 	1 0 -1	; _ENV "string"
	2	[2]	GETTABLE 	1 1 -2	; "gmatch"
	3	[2]	MOVE     	2 0
	4	[2]	LOADK    	3 -3	; "foo"
	5	[2]	TAILCALL 	1 3 0
	6	[2]	RETURN   	1 0
	7	[3]	RETURN   	0 1

function <test-str-mtab.lua:5,7> (5 instructions at 0x1ad4b90)
1 param, 4 slots, 0 upvalues, 1 local, 2 constants, 0 functions
	1	[6]	SELF     	1 0 -1	; "gmatch"
	2	[6]	LOADK    	3 -2	; "foo"
	3	[6]	TAILCALL 	1 3 0
	4	[6]	RETURN   	1 0
	5	[7]	RETURN   	0 1