I decided to, after a long time of inactivity on it, revisit my GitHub account and the content there. While reorganising one of my repositories full of free code samples I’ve dumped for public use, I had the urge to add a function to my TableUtility library (formerly Array), “DictionarySelectRandom”.
As you can probably tell by the function’s name, the intention of the function is to allow the developer to select a random item from a dictionary. A simple random statement won’t do the trick so needing to create a function to do so is necessary. Now who would ever need it, I don’t know, you never usually apply randomised selections for a dictionary.
I wrote this on the fly just now and don’t have any ideal testing environments to put this through other than spam loops in blank baseplates. The function is available as follows:
function TableUtility.DictionarySelectRandom(dictionary)
local keys = {}
for key, _ in pairs(dictionary) do
table.insert(keys, key)
end
if #keys == 1 then
local onlyKey = keys[1]
return dictionary[onlyKey]
end
local position = Random.new():NextInteger(1, #keys)
local key = keys[position]
return dictionary[key]
end
Now the reason I put “performance concerns” in the thread title is because obviously I’m concerned about the performance of this function, but also because the repository is open source. I don’t know who looks through my GitHub, if anyone at all, and if I’m sharing them code that isn’t performant, that wouldn’t bode well with me.
The only thing I’ve considered so far to improve performance is to use table.create so that the keys array isn’t getting resized every time a new entry is inserted. I don’t know what else I can do to make this more performant; and if it’s worth even fretting about at all. Any insight?
PS: I will not sacrifice readability for performance unless the latter reduces the time the function takes to run by a significant amount.
Complete library:
Thank you in advance.