Created
February 8, 2024 20:21
-
-
Save appgurueu/4117ad8ddf9b810e9f1538792c6ea69d to your computer and use it in GitHub Desktop.
Rudimentary benchmarking of closure-based vs metatable-based OOP in Lua
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
-- Usage: luajit bench.lua (closures|metatables) | |
local Foobar = require((...)) | |
for _ = 1, 5 do | |
local t = os.clock() | |
local sum = 0 | |
for i = 1, 1e6 do | |
sum = sum + Foobar("foo", i, "baz"):get_bar() | |
end | |
print("dt", os.clock() - t, "sum", sum) | |
end |
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
return function(foo, bar, baz) | |
local self = {} | |
-- This could be slightly optimized by putting them in a table constructor | |
function self.get_foo() return foo end | |
function self.set_foo(new_foo) foo = new_foo end | |
function self.get_bar() return bar end | |
function self.set_bar(new_bar) bar = new_bar end | |
function self.get_baz() return baz end | |
function self.set_baz(new_baz) baz = new_baz end | |
function self.frobnicate() print(foo, bar, baz) end | |
return self | |
end |
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
local foobar = {} | |
function foobar:get_foo() return self.foo end | |
function foobar:set_foo(new_foo) self.foo = new_foo end | |
function foobar:get_bar() return self.bar end | |
function foobar:set_bar(new_bar) self.bar = new_bar end | |
function foobar:get_baz() return self.baz end | |
function foobar:setBaz(new_baz) self.baz = new_baz end | |
function foobar:frobnicate() print(self.foo, self.bar, self.baz) end | |
local mt = {__index = foobar} | |
return function(foo, bar, baz) | |
return setmetatable({foo = foo, bar = bar, baz = baz}, mt) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment