Longest string in array (v5)

Revision 5 of this benchmark created by Timo on


Preparation HTML

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

Test runner

Ready to run.

Testing in
TestOps/sec
Straight
function Ls(a) {
  var l = 0;
  for (var i = 0; i < a.length; i++) {
    if (a[l].length < a[i].length) l = i;
  }
  return l;
}
var longest = arr[Ls(arr)];
ready
Optimized
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 li;
}
var longest = arr[Lo(arr)];
ready
Straight2
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 l;
}
var longest = arr[Ls2(arr)];
ready
timo_longest
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 l;
}
var longest = arr[timo_longest(arr)];
ready
Reduce
var longest = arr.reduce(function(a, b) {
  return a.length > b.length ? a : b;
});
ready
Sort
var longest = arr.sort(function(a, b) {
  return b.length - a.length;
})[0];
ready

Revisions

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