Mega trim test (v22)

Revision 22 of this benchmark created by Timo on


Description

Trim function

Preparation HTML

<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

Ready to run.

Testing in
TestOps/sec
trim1
e(trim1);
ready
trim2
e(trim2);
ready
native
e(trim_native);
ready

Revisions

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