Longest string in array (v12)

Revision 12 of this benchmark created by Dawid on


Preparation HTML

<script>
  var arr = ['adf', 'asdfdf', 'asdfdf', 'aasdfdf', 'addddddf', 'asdfdf', 'assdf', 'adfd'];

function Ls(a) {
  var l = 0;
  for (var i = 0; i < a.length; i++) {
    if (a[l].length < a[i].length) l = i;
  }
  return a[l];
}

function Lo(a) {
  var li = 0,
      ll = a[0].length !== 0 ? a[0].length - 1 : 0;
  for (var i = 0; i < a.length; i++) {
    if (a[i][ll]) {
      ll = a[i].length - 1;
      li = i;
    }
  }
  return a[li];
}

function Ls2(a) {
  var l = a.length - 1;
  var i = l;
  if (i) while (i--) if (a[l].length < a[i].length) l = i;
  return a[l];
}

function timo_longest(a) {
  var c = 0,
      d = 0,
      l = 0,
      i = a.length;
  if (i) while (i--) {
    d = a[i].length;
    if (d > c) {
      l = i;
      c = d;
    }
  }
  return a[l];
}

var Sort = function(arr)
{
  return arr.sort(function(a, b) {
  return b.length - a.length;
})[0];
};

var Reduce = function(arr)
{
  return arr.reduce(function(a, b) {
  return a.length > b.length ? a : b;
});
}
function longestStr(a) {
    var i=a.length - 1,m=0,j=0;
    for(i; i >= 0; i--) {
       if(a[i].length > m){
           m=a[i].length;
           j=i;
       }
    }return a[j];
}
function longestLength(a) {
    var i=a.length - 1,m=0,j=0;
    for(i; i >= 0; i--) {
       m = Math.max(a[i].length, m);
    }return m;
}

function longestLengthVerbose(a) {
    var l = a[0].length,
        i = 1;
    for (; i < a.length; i++) {
        if (l < a[i].length) {
            l = a[i].length;
        }
    }
    return l;
}

</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Straight
var longest = Ls(arr);
ready
Optimized
var longest = Lo(arr);
ready
Straight2
var longest = Ls2(arr);
ready
timo_longest
var longest = timo_longest(arr);
ready
Sort
var longest = Sort(arr);
ready
Reduce
var longest = Reduce(arr);
ready
one less var,more .length references
var longest = longestStr(arr);
ready
Return length, not string
var longest = longestLength(arr);
ready
Return length, not string (verbose)
var longest = longestLengthVerbose(arr);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.