lua-users home
lua-l archive

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


Hi guys,

In our recent debates about OOP styles in Lua some
people didn't like saying 'self' to qualify object
fields all the time.  The quick way to dispose with
self is to use setfenv() to set the local context.
Unfortunately, this does turn out to be
an expensive operation. 

Here's the test case:

local setfenv = setfenv
local N = 10

T = class(function(self)
        self.x = 1
        self.y = 2
        self.z = 3
   end)

function T:go1()
  self.x = 1
  for i = 1,N do self.x = self.y + self.z end
end

function T:go2()
  setfenv(1,self)
  x = 1
  for i = 1,N do x = y + z end
end

Both the methods go1 and go2 achieve the same
(nonsensical) result, except that go2 makes the
object context implicit. The test is to call
these methods a million times; times are
reported in seconds.

      N=3  N=10  N=20 N=40
go1 3.4   6.3     11.1   21.3 
go2 4.7   7.2     11.3   20.0

Eventually, if you have a lot of operations,
the setfenv method gets a little faster, but
it doesn't break even quickly!   

Of course, setfenv does not help you with
method dispatch - self is not automatically
passed to methods called in this way.

steve d.