From 8baa1f138800d5c68455bdba944a9a7429ed563b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 11:30:29 -0500 Subject: [PATCH] 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. --- compat/luajit.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/compat/luajit.lua b/compat/luajit.lua index 72cb133..2a6bfc9 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -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