Sort First or Find Max Only for Optimization?

  1. What do you want to achieve?
    I want to be able to find the best-optimized path to finding the max value of something

  2. What is the issue?
    I have not done a benchmark test, so I am out to ask if I can receive a quick answer from DevForum. Otherwise, I will conduct the benchmark test on my own.

  3. What solutions have you tried so far?
    I’ve attempted to look around the DevForum to see if I can find any answers related to what I asked, but I don’t think I was able to find a similar problem (or if I didn’t look hard enough).

-- Sort and Find Max
table.insert(playerScores, {"Roblox", 1})
table.insert(playerScores, {"OtherPlayer", 2})
table.insert(playerScores, {"NewPlayer", 3})

table.sort(playerScores, function(a, b)
	return a[2] > b[2] -- compare current player to next player
end)

local max = playerScores[1]
-- max is NewPlayer

-- Find Max only
local maxPlayer = nil
local maxScore = 0

for _, player in pairs(playerScores) do
	if maxPlayer == nil then
		maxPlayer = player[1]
		maxScore = player[2]
		continue
	end
	
	if player[2] > maxScore then
		maxPlayer = player[1]
		maxScore = player[2]
		continue
	end
end
1 Like

table.sort is the meta

Really depends on the use case. Sorting of the same table will always be slightly less efficient than solely iterating alone. But if, for example, first five places are needed, it is much more convenient to sort.

My advice is, don’t worry about micro-optimizations too much. Find a balance between optimization, good practices, readability, and convenience for your situation.

If you’re only getting the top score, linear search on an unsorted table is an excellent choice. Linear search works with O(n) efficiency, so in the worst case scenario, the highest score is the last player. And the table is so small the difference is negligible.

I’ve done a quick test with a 1000-element long table. We’re speaking of values much lower than half a millisecond! Worst case scenario in a for-loop takes a couple of microseconds, and sorting took about 40 times longer, which is a couple hundred micro seconds.

Literally microscopic times! It’s much more likely that a render update might throttle or dozens of other things to impact performance.

1 Like