lua-users home
lua-l archive

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


On Thu, 14 Aug 2014 19:28:39 -0700
Tim Hill <drtimhill@gmail.com> wrote:

> 
> On Aug 14, 2014, at 6:07 PM, Jan Behrens <jbe-lua-l@public-software-group.org> wrote:
> 
> > This is due to the fact that ipairs is a baselib function that utilizes
> > the iterator triplet construct (which in turn allows us to store only
> > one state variable, while we would need two state variables here). If
> > ipairs was a language construct that just behaves like "for i = 1, #t
> > do local v = t[i]; ... end", then we wouldn't have a problem here.
> 
> But that one state variable can contain a table, so you can store as much state as you want.
> 
> ?Tim
> 

That is correct. But also consider:

> > Creating tables or closures, however, would have an even greater
> > perfomance impact.


Creating tables to contain multiple state variables is possible.
However, in case of nested loops, this can get quite nasty. Consider:

========================================
function some_func(s, i)
  local t, len = table.unpack(s)
  if i < len then
    i = i + 1
    return i, t[i]
  else
    return nil
  end
end

t = {"a", "b", "c"}

for n = 1, 10000 do
  for i, v in some_func, {t, #t}, 0 do
    -- do something with i and v here
  end
end
========================================

This construct will create 10000 tables (which need to be collected by
the garbage collector later).

Another option is to create closures:

========================================
function another_func(t, len)
  local pos = 0
  return function()  -- create and return a closure
    if pos < len then
      pos = pos + 1
      return pos, t[pos]
    else
      return nil
    end
  end
end

t = {"a", "b", "c"}

for n = 1, 10000 do
  for i, v in another_func(t, #t) do
    -- do something with i and v here
  end
end
========================================

But also here, 10000 objects are created: the functions that are
created and returned by another_func(t, #t). Also these functions need
to be collected by the garbage collector later.


Often we don't care much about creating tables or closures. But if a
simple loop causes a memory allocation (and garbage collection later),
then this might have a bad impact on the overall performance of the
language.


Regards
Jan