Re:Math.min(Math.max(num, min), max)
by gridlockd on Thursday August 20, 2020 @12:58PM
(#24225478)
This is why computers are slow.
[ Parent
| on HN ]
I was curious how slow this would be, and here is what JavaScriptCore made of this code:
function clamp(n, min, max) {
return [min, n, max].sort((a, b) => a - b)[1];
}
for (var i = 0; i < 10000000; i++) {
clamp(Math.random() | 0, Math.random() | 0, Math.random() | 0);
}
However, I was pretty disappointed when it seemed to be calling sort each time :( Perhaps I profiled it incorrectly? jsc's profiling data shows that it never hit FTL and nothing ever got inlined. The bytecode for DFG and Baseline is identical: Compilation clamp#CChm91-1-Baseline:
arg0: predicting OtherObj
arg1: predicting BoolInt32
arg2: predicting BoolInt32
arg3: predicting BoolInt32
[ 0] enter
[ 1] get_scope loc4
[ 3] mov loc5, loc4
[ 6] check_traps
[ 7] mov loc11, arg2
[ 10] mov loc12, arg1
[ 13] mov loc13, arg3
[ 16] new_array loc10, loc11, 3, 3
[ 22] get_by_id loc7, loc10, 0
[ 27] new_func_exp loc9, loc4, 0
[ 31] call loc7, loc7, 2, 16
[ 37] get_by_val loc6, loc7, Int32: 1(const0)
[ 42] ret loc6
Compilation clamp#CChm91-2-DFG:
arg0: predicting OtherObj
arg1: predicting BoolInt32
arg2: predicting BoolInt32
arg3: predicting BoolInt32
[ 0] enter
[ 1] get_scope loc4
[ 3] mov loc5, loc4
[ 6] check_traps
[ 7] mov loc11, arg2
[ 10] mov loc12, arg1
[ 13] mov loc13, arg3
[ 16] new_array loc10, loc11, 3, 3
[ 22] get_by_id loc7, loc10, 0
[ 27] new_func_exp loc9, loc4, 0
[ 31] call loc7, loc7, 2, 16
[ 37] get_by_val loc6, loc7, Int32: 1(const0)
[ 42] ret loc6Dude, you are generating random numbers inside the loop. That is going to dominate runtime.
I'm not testing runtime, though, I'm testing whether clamp gets optimized.
Re:Math.min(Math.max(num, min), max)
by secondcoming on Thursday August 20, 2020 @01:39PM
(#24226049)
No. Just things written by web devs.
(Shots fired)