Is this code efficient for comparing/contrasting two tables?

Is this code below a good/efficient way to check if two arrays/tables are the same or not. If the tables are the same, it will return true and then remove any functions in the table. If the tables are not the same then it would return and say false.

local _FOLDER = {
	Test = 1;
	Test2 = 6;
}

local _FOLDER2 = {
	Test = 1;
}


local HTTPService = game:GetService("HttpService")
local Same = HTTPService:JSONEncode(_FOLDER)==HTTPService:JSONEncode(_FOLDER2)

local function Reconcile(arr)
	for nam,obj in pairs(arr) do
		if typeof(obj) == "function" then
			arr[nam] = nil
			--Remove the function item from the table so that the dataStore can save successfully.
			--[NOTE: You cannot save functions.] 4/11/22
		elseif typeof(obj) == "table" then
			Reconcile(obj)
		end
	end
end

if Same == true then
	Reconcile(_FOLDER)
	print(_FOLDER)
else
	print(Same)
end
1 Like

I see my bit of code in that :slight_smile:

arr[nam] = nil
may not be efficient, as it doesn’t call garbage collection. Instead do this:
table.remove(arr, table.find(arr, nam))

1 Like

ye It’s the one I showed you
ㅤㅤ
ㅤㅤ
ㅤㅤ
ㅤㅤ
ㅤㅤ
ㅤㅤ
ㅤㅤ
ㅤㅤ

Setting a key to nil is the same as removing it from the table as far as the garbage collector is concerned.

1 Like

Creative way on how to compare two tables, it’s definitely shorter solution, however the process is little bit inefficient.
The table must be serialized and put into new string object and then compared.

Another solution what you could do is deep-compare of the table and return false on first difference.
Why it’s better is because there’s no need to check other entries if a difference is found.
Obviously the worst case scenario for performance is when the tables are same, since the compare must fully check both tables, but at the end it’s still more efficient than doing serialization and string creation.

1 Like

table.find() uses a linear search. In that case it would be slower. Also table.find doesn’t work on values indexed by anything other than a number.

it’s simplicity and speed is pretty ok but if you need speed this is the function to use:

function module.isSameTable(tab1 :{}?, tab2 :{}?) :boolean
	if type(tab1) ~= "table" or type(tab2)~="table" then return false end
	if tab1==tab2 then return true end
	for k,v in pairs(tab1) do
		if tab2[k] ~= v and not module.isSameTable(v,tab2[k]) then
			return false
		end
	end
	for k,v in pairs(tab2) do
		if tab1[k] ~= v and not module.isSameTable(v,tab1[k]) then
			return false
		end
	end
	return true
end
2 Likes