ws-cleanup: compat math.clamp through math.min / math.max (LuaJIT)

The branchy compat clamp spawned side traces in hot loops: ~3.5x slower than min(max(x, lo), hi) in a
microbenchmark (NaN still passes through, as in Luau). MPEG-1 320x240 to rgba on LuaJIT (tuned traces):
2.92 -> 2.13 ms/frame.
This commit is contained in:
4DBug committed 2026-10-31 11:30:29 -05:00
1 parent 4478332a61
commit 8baa1f1388
1 file changed
+6 -2
+6 -2
View File
@@ -476,10 +476,14 @@ end
-- ---------------------------------------------------------------------------------------------------- math
do
-- math.min / math.max are LuaJIT fast functions (branch-free minsd / maxsd in a trace); the two data-dependent
-- branches of `if x < lo ... elseif x > hi` spawned side traces in hot loops (codecs/Dct, colour conversion) and
-- ran ~3.5x slower. NaN stays NaN, as in Luau (maxsd would return lo).
local mmin, mmax = math.min, math.max
math.clamp = math.clamp or function(x, lo, hi)
if lo > hi then error("max must be greater than or equal to min", 2) end
if x < lo then return lo elseif x > hi then return hi end
return x
if x ~= x then return x end
return mmin(mmax(x, lo), hi)
end
math.sign = math.sign or function(x)
if x > 0 then return 1 elseif x < 0 then return -1 end