lua-users home
lua-l archive

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


I am experimenting with things that would let one to imply <self.> instead of typing it. Below is the idea that works so far. Basically, implicit <self.> slows calls by a factor of 10-20. But with some code the difference is more like 3x. Any other ideas on how to do the same sort of thing would be appreciated. The reason I am experimenting with this is to eliminate a source of bugs/typos and make the source more readable (in the context of our scripting environment). Basically the desired convention would be to make any unqualified names refer to <self> or whatever metatable chains it might have unless it's a local.

Thanks,
Alex


---------- CUT HERE ---------------------------------------------

Class = {}

function Class:Method(i)
   JJ = i
   while(i > 0) do
      i = i - 1
      if(i>4) then JJ = JJ*2; end 
      if(i>3) then JJ = JJ-2; end 
      if(i>2) then JJ = JJ+2; end 
      if(i>1) then JJ = JJ/2; end 
   end
end

function Class:EmptyMethod(i)
end

ClassInst = setmetatable({}, {__index = _G})

function ClassInst.Method(...)
   setfenv(Class.Method, ClassInst)
   Class.Method(unpack(arg))
end

function ClassInst.EmptyMethod(...)
   setfenv(Class.EmptyMethod, ClassInst)
   Class.EmptyMethod(unpack(arg))
end

-- Timing
local N = 55555
local t


t = os.clock()
for k = 0, N do
   Class:EmptyMethod(5)
end
print('Empty Calls/msec : '..tostring(math.floor(N*0.001/(os.clock() - t))))

t = os.clock()
for k = 0, N do
   ClassInst:EmptyMethod(5)
end
print('Empty Env Calls/msec : '..tostring(math.floor(N*0.001/(os.clock() - t))))

t = os.clock()
for k = 0, N do
   Class:Method(5)
end
print('Calls/msec : '..tostring(math.floor(N*0.001/(os.clock() - t))))

t = os.clock()
for k = 0, N do
   ClassInst:Method(5)
end
print('Env Calls/msec : '..tostring(math.floor(N*0.001/(os.clock() - t))))

print(JJ) -- for class it's global JJ
print(ClassInst.JJ) -- for instance it's JJ in the env table, which is ClassInst itself