News for hackers. Stuff that matters.
Re:Math.min(Math.max(num, min), max) by saagarjha on Thursday August 20, 2020 @03:52PM (#24227979)
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                loc6
Re:Math.min(Math.max(num, min), max) by garmaine on Thursday August 20, 2020 @06:42PM (#24229870)
Dude, you are generating random numbers inside the loop. That is going to dominate runtime.
Re:Math.min(Math.max(num, min), max) by saagarjha on Thursday August 20, 2020 @06:56PM (#24229984)
I'm not testing runtime, though, I'm testing whether clamp gets optimized.