2 Replies Latest reply on Sep 19, 2008 10:36 AM by (Dave_Saunders)

    Sometimes brevity isn't best

    Level 1
      I needed to get the max value of an array (of numbers).

      I've long had in my repertoire this function:
        function getMax(anArray) { // anArray is array of numbers
      
          var max = Number.NEGATIVE_INFINITY;
          for (var j = anArray.length - 1; j >= 0; j--) {
            max = Math.max(max, anArray[j]);
          }
          return max
        }
      But this morning, I tried this alternative, which has the "advantage" of reducing the body of the function to a single line:
        function getMax(anArray) {
      
          return anArray.sort(function(a,b) {return b-a})[0];
        }
      A timing test reveals that this briefer version takes about 40% longer to run. This is obviously caused by all the extra comparisons that are needed to sort the whole array, when all you really need to do is shuffle the largest one to the top (so to speak).

      Dave
        • 1. Re: Sometimes brevity isn't best
          Level 1
          > A timing test reveals that this briefer version takes about 40% longer to run. This is obviously caused by all the extra comparisons that are needed to sort the whole array, when all you really need to do is shuffle the largest one to the top (so to speak).

          Try this. It replaces the Math.max() with a comparison operation so it should be
          noticeably faster.

          function getMax(anArray) { // anArray is array of numbers
          var max = Number.NEGATIVE_INFINITY;
          for (var j = anArray.length - 1; j >= 0; j--) {
          var x = anArray[j];
          if (x > max) {
          max = x;
          }
          }
          return max
          }


          -X
          --
          for photoshop scripting solutions of all sorts
          contact: xbytor@gmail.com
          • 2. Re: Sometimes brevity isn't best
            Level 1
            Interesting thought, but it's giving essentially the same times as using the Math.max function. If anything a tad slower on average, but one run was the fastest I've seen yet. My test is somewhere around 1 second long; I could probably do with using a longer array to get a more refined picture.

            Thanks,

            Dave