Table.sort optimizations

lets say i do

table.sort(t,function(a,b)
      return someExpensiveFunction(a)>someExpensiveFunction(b)
end)

That comparator function will almost certainly be ran multiple times with at least 1 of the same entries (uses some quicksort hybrid alg from the minimal research i did)

But does the compiler optimize for me and know to only call someExpensiveFunction once per entry and then cache it, or would there be multiple calls?

1 Like

No, the compiler would not cache it for you. There would be multiple calls. This is because it would call your function every time it needs to compare the two elements.

2 Likes

As the previous person said, no, you have to do it:

local cache = {}
for _, v in pairs(t) do
	cache[v] = someExpensiveFunction(v)
end
table.sort(t, function(a, b)
	return cache[a] > cache[b]
end)
1 Like