Created
December 14, 2011 10:57
-
-
Save bjorn/1476120 to your computer and use it in GitHub Desktop.
Lua OOP benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This benchmark compares two ways of creating objects. | |
-- Output commonly seen on the Lua demo site: | |
-- | |
-- Creation time: 0.16 | |
-- Calling member function time: 0.11 | |
-- Memory: 2868.8798828125 | |
-- | |
-- Creation time: 0.11 | |
-- Calling member function time: 0.13 | |
-- Memory: 1697.4736328125 | |
-- | |
-- Showing the second method definitely has the edge in | |
-- both speed and memory. | |
local clock = os.clock | |
local Fruit = function(self) | |
self.weight = self.weight or 0 | |
self.color = self.color or "undefined" | |
function self:eat() | |
self.weight = 0 | |
end | |
return self | |
end | |
local start = clock() | |
for i=1,100000 do | |
local fruit = Fruit {} | |
end | |
print("Creation time:", clock() - start) | |
local fruit = Fruit {} | |
local start = clock() | |
for i=1,1000000 do | |
fruit:eat() | |
end | |
print("Calling member function time:", clock() - start) | |
local fruits = {} | |
for i=1,10000 do | |
fruits[i] = Fruit {} | |
end | |
collectgarbage("collect") | |
print("Memory:", collectgarbage("count")) | |
local funcs = {} | |
local meta = { __index = funcs } | |
function funcs:eat() | |
self.weight = 0 | |
end | |
local CreateFruit = function(self) | |
self.weight = self.weight or 0 | |
self.color = self.color or "undefined" | |
return setmetatable(self, meta) | |
end | |
local start = clock() | |
for i=1,100000 do | |
local fruit = CreateFruit {} | |
end | |
print("Creation time:", clock() - start) | |
local fruit = CreateFruit {} | |
local start = clock() | |
for i=1,1000000 do | |
fruit:eat() | |
end | |
print("Calling member function time:", clock() - start) | |
for i=1,10000 do | |
fruits[i] = CreateFruit {} | |
end | |
collectgarbage("collect") | |
print("Memory:", collectgarbage("count")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment