The built-in function Clip is defined as a way to clip a value between a specified minimum and maximum. Another way to do this, is simply by utilizing Min and Max methods. e.g. Clip[#,{1,3}]& is basically equivalent to #~ Min~ 3~ Max~ 1&, but it seems Clip is way slower. Here are two tests:

AbsoluteTiming[# ~Min~3 ~Max~1 & /@ RandomReal[{0, 5}, 10^7];]
AbsoluteTiming[Clip[#, {1, 3}] & /@ RandomReal[{0, 5}, 10^7];]

The first one returns {0.482735, Null} and the second result is {6.13182, Null} which means Clip is about thirteen times slower. Now this might not seem a big issue since I doubt that anybody cares about the speed of such function, and it has an easy fix by the anyway. But I am just curious, why does this happen? In a parallel world where the humanity cannot access the Min and Max functions and they are stuck with Clip, how can they optimize it?

  • 6
    $\begingroup$ You only need to call Clip once: AbsoluteTiming[Clip[RandomReal[{0, 5}, 10^7], {1, 3}]] $\endgroup$
    – Coolwater
    Nov 16 '21 at 10:33
  • 2
    $\begingroup$ Yes! Clip isn't slow. But Map is. $\endgroup$ Nov 16 '21 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.