Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Opinion on which function would be most efficient for Cloning a Table?

So I have created 2 functions, each covering a feature Lua does not offer: copying a table. Would just like a more mindful opinion of Which would be more efficient.

1:

_G.MakeCopyOfTable = function(original)
	local copy = {}
	for k, v in pairs(original) do
		if type(v) == 'table' then
			v = _G.MakeCopyOfTable(v)
		end
		copy[k] = v
	end
return copy
end

2:

local hs = game:GetService("HttpService")
_G.MakeCopyOfTable = function(original)
	return hs:JSONDecode(hs:JSONEncode(original))
end

So function 1 loops through the table and creates a clone for every property, whilst function 2 takes the table, encodes it into JSON, and immediately decodes it to a table. Both functions work as intended, but as this function for my script will run roughly 30 times instantly, I would like another opinion as to which I should use for the most efficient / least lag possible. All answers appreciated.

1 answer

✓ Accepted answer

Probably the first function, as JSONEncode() most probably has to loop through all the elements of the table anyway.

You really shouldn't worry about cloning a table efficiently unless you start having efficiency problems. Until then, a single { unpack(t) } for array-like tables or a generic for loop should be okay.

This discussion is preserved as it was. New answers, comments, and votes are closed.