Mega trim test (v39)

Revision 39 of this benchmark created by ! on


Description

Testing "trim-native" and "trim27" (from rev7) with the following trim functions:

Preparation HTML

<script>
  function trim27(str) {
    var c;
    for (var i = 0; i < str.length; i++) {
        c = str.charCodeAt(i);
        if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12) continue; else break;
    }
    for (var j = str.length - 1; j >= i; j--) {
        c = str.charCodeAt(j);
        if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12) continue; else break;
    }
    return str.substring(i, j + 1);
}

  function trim_native(str) {
         return str.trim(); // should throw is no such function
  }

  function trim19(str){
      var str = str.replace(/^\s\s*/, ''),
          ws = /\s/,
          i = str.length;
      while (ws.test(str.charAt(--i)));
      return str.slice(0, i + 1);
  }
  // Licensed under BSD - http://flesler.blogspot.com/2008/11/fast-trim-function-for-javascript.html
  function myBestTrim( str ){
    var start = -1,
      end = str.length;
    while( str.charCodeAt(--end) < 33 );
    while( str.charCodeAt(++start) < 33 );
    return str.substring( start, end + 1 );
  };

  var inp = "    \n\n \n\n   a \n a\n  a\n    a\n   a  \n\t\ta\t\ta\njahsdkjahkjshdakjhsdkahskd akhsjdh akjshd kashdkajhsd kajshd \nkauyiuqhwep iasldk qpwoie ad  \n   askdjaslkdjaslkjdaoiur qowioqwhr aspodiquw ijasod iqwiue pqowipoqiw epoqiwpeo iaslkjdqur \t kjahsdkj hakshd\nkajhdk\nk as d  \t\n".split('\n');
  
  function e(f) {
     var x = [];
     for (i = 0; i < inp.length; i++) {
       x.push(f(inp[i]));
     }
     return x;
  }
//it's unfair to wrap the native function, within an outer dummy function since this doesn't represent real world usage
function native(){
     var x = [];
     for (i = 0; i < inp.length; i++) {
       x.push(inp[i].trim());
     }
     return x;
}
</script>

Setup

//Need to reset input after each time, otherwise subsequent tests have advantage cause the string doesn't have whitespace
    inp = "    \n\n \n\n   a \n a\n  a\n    a\n   a  \n\t\ta\t\ta\njahsdkjahkjshdakjhsdkahskd akhsjdh akjshd kashdkajhsd kajshd \nkauyiuqhwep iasldk qpwoie ad  \n   askdjaslkdjaslkjdaoiur qowioqwhr aspodiquw ijasod iqwiue pqowipoqiw epoqiwpeo iaslkjdqur \t kjahsdkj hakshd\nkajhdk\nk as d  \t\n".split('\n');

Test runner

Ready to run.

Testing in
TestOps/sec
trim-native
native();
ready
trim27
e(trim27);
ready
trim19
e(trim19)
ready
myBestTrim
e(myBestTrim);
ready

Revisions

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