lua-users home
lua-l archive

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


>From: David Jeske <jeske@home.chat.net>
>
>I have a question for the Lua implementors though. What are the
>performance implications of putting this table initialization syntax
>within a function call? What is the overhead of putting the above example in a function vs doing it like this:
>
>switch_tbl = {
>    [1] = function (x) B1 end,
>    [2] = function (x) B2 end,
>    ["nop"] = function (x) B3 end,
>    ["my name"] = function (x) B4 end,
>    ["__default__"] = function (x) B5 end
>};
>
>function a()
>   Switch(switch_var,{arg1,arg2},switch_tbl);
>end

I'm not sure what you mean here.
If you want to know whether there is any overhead in defining "local" functions,
then the answer is no: functions are always compiled just once, even if they
contain upvalues.

On the other hand, if a table is going to be used very frequently, then it's
faster to save it in a variable. In other words:

  i=0
  while i<1000 do
	  f{a=1,b=2,c=3,...}	-- long table
	  i=i+1
  end

is "slower" than 

  do
  local t={a=1,b=2,c=3,...}	-- long table
  i=0
  while i<1000 do
	  f(t)
	  i=i+1
  end
  end

If t is slighty different for each i (otherwise, what's the point), then
it's still better to use the second form and just change the new fields:

  do
  local t={a=1,b=2,c=3,...}	-- long table
  i=0
  while i<1000 do
	  t.i=i
	  f(t)
	  i=i+1
  end
  end

Now, as I have been pointing out lately, "slow" and "fast" are very relative.
As a programmer, I also feel this urge to make everything fast, but you have
to keep in mind that the loop overhead (i<1000, i=i+1) is probably comparable
to anything else.
So, I'd go for the more readable code, whatever it is.
--lhf