Mega trim test

JavaScript performance comparison

Revision 22 of this test case created by Timo and last updated

Info

Trim function

Preparation code

<script>
var native_trim = ''.trim;

var trim1 = function(str) {
  if (str == null) {
    return '';
  }
  var c;
  var l = str.length;

  str = String(str);
  for (var i = 0; i < l; i++) {
    c = str.charCodeAt(i);
    if (c < 8192) {
      if (c < 256 && (c == 32 || (c >= 9 && c <= 13) || c == 160)) continue;
        else if (c == 5760 || c == 6158) continue;
        break;
      } else if (c <= 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288) continue;
    break;
  }
  for (var j = str.length - 1; j >= i; j--) {
    c = str.charCodeAt(j);
    if (c < 8192) {
      if (c < 256 && (c == 32 || (c >= 9 && c <= 13) || c == 160)) continue;
      else if (c == 5760 || c == 6158) continue;
      break;
    } else if (c <= 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288) continue;
    break;
  }
  return str.slice(i, j + 1);
};

var trim2 = function(string) {
  if (string == null) {
    return '';
  }
  var start = -1,
      end = string.length;

  string = String(string);
  var c;

  while (++start < end && isWhitespace(string, start)) { }
  while (end-- && isWhitespace(string, end)) { }
  return string.slice(start, end + 1);
};

function isWhitespace(string, index) {
  var c = string.charCodeAt(index);
  return (
    (c <= 160 && (c >= 9 && c <= 13) || c == 32 || c == 160) || c == 5760 || c == 6158 ||
    (c >= 8192 && (c <= 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279))
  );
}

function trim_native(str) {
  return str == null ? '' : native_trim.call(str);
}

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, l = inp.length; i < l; i++) {
    x.push(f(inp[i]));
  }
  return x;
}
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
trim1
e(trim1);
pending…
trim2
e(trim2);
pending…
native
e(trim_native);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment