Just for my curiousity, does the so-called hashing (don’t actually know the word) cause memory leaks?
For example
local hashes = { };
function example(v)
if hashes[v] then
return hashes[v];
end;
local proxy = newproxy(true);
hashes[v] = proxy;
return proxy;
end;
print(rawequal(example(1), example(1))) --> true
where it seems like it’s passed by value instead of reference
as opposed to
function example(v)
local proxy = newproxy(true);
return proxy;
end;
print(rawequal(example(1), example(1))) --> false
and what would be a much more memory efficient way?
The reason that leads me thinking into causing memory leaks is because apparently tables are garbage collected if there are no more references passed, that this doesn’t seem to be the case as there are still references, I am uncertain whether this can cause memory leaks and which one would be more memory efficient?
Don’t know if this belongs here, can’t find anywhere else that this belongs.
What you are doing resembles memoization. Memoization is an optimization technique where you turn a function’s results into something that will be remembered. Take this example:
local function fibonacci(n)
if n <= 1 then
return n
end
return fibonacci(n - 1) + fibonacci(n - 2)
end
print(fibonacci(5))
print(fibonacci(5))
You are unnecessarily re-computing it again with the same argument! That is where memoization comes to the rescue:
local cache = { }
local function fibonacci(n)
if cache[n] ~= nil then
return cache[n]
end
if n <= 1 then
return n
end
local result = fibonacci(n - 1) + fibonacci(n - 2)
cache[n] = result
return result
end
If the function has already been called with the same argument, it will look up a result in the cache table and return that instead of unnecessarily computing the same result again.
The more objects you pass in, the more the cache table builds up. This is why you generally shouldn’t memoize functions that take objects, such as userdata in your example.
You could do
setmetatable(cache, { __mode = "kv" })
to solve this though.
But could you explain why you need to store objects like this?