In terms of the size/functionality of the original table, how expensive is it to create a new metatable just for this specific table? Is it any more expensive than sharing a metatable with other tables? On what specific meta methods might it be even more significant?
A metatable should be no more expensive than a normal table, since that’s basically all it is.
As @Kampfkarren said, it’s just a normal table.
You may be referring to attaching a metatable to a table instead (setmetatable), and this is as expensive as any normal function call on the Lua end.
Not expensive enough to need to care about it
Its not any more expensive, I ran a few tests (running the same thing 100k times).
Im not 100% sure if the tests are what you were asking about but I tried.
But as you can see at the bottom of the script the speed difference is so small you shouldnt have to optimize it.
local t = tick()
for i = 1, 100000 do
local t = {}
end
local t2 = tick()
local tabl = {}
for i = 1, 100000 do
setmetatable(tabl,{})
end
local t3 = tick()
for i = 1, 100000 do
local tabls = {}
setmetatable(tabls,{})
end
local function func()
return
end
local t4 = tick()
for i = 1, 100000 do
local tabls = {}
func()
end
print(tick()-t) -- Output: 0.03519 < fastest
print(tick()-t2) -- Output: 0.05942
print(tick()-t3) -- Output: 0.08039 < slowest (creating table and using setmetatable on it)
print(tick()-t4) -- Output: 0.05601
besides the values stored in a metatable that a normal table could store, do metatables hold any extra information? (including the meta method lua functions)
And if so, does it depend on the number of tables that use it as a metatable or is it constant or?
Nope. Metatables are just tables.
It’s not the expense that you should care about, it’s the structure.
If you have a metatable that’s only used for one table then you should be asking yourself whether using a metatable is correct at all in the first place. The point of metatables is generally to define classes of object with special behavior (In which case the whole class of objects would share one metatable). If you just have a one-off object it’s probably a bad idea to give it it’s own special behavior because then you’ll have one thing awkwardly acting differently from everything else in your code—one extra special case to remember.
You should reuse things when you can in programming and reusing a meta table should save on memory as well.