trim()

JavaScript performance comparison

Test case created by sofish

Info

trim 性能

Preparation code

<input id="theinput" value="     dslakfjdls     dlskafjdslaf    ldsakfjdlskaf    lsdakfjdslka   sdlkafjdlska    sdlafkjdslkajf    "/>
<script>
  Function.prototype.method = function(name, func) {
   this.prototype[name] = func;
   return this;
  };
 
  String.method('trimReg', function() {
   return this.replace(/^\s+|\s+$/g, '');
  });
 
  String.method('trimSemiReg', function() {
   var str = this.replace(/^\s+/, '');
   for (var i = str.length - 1; i >= 0; i--) {
    if (/\S/.test(str.charAt(i))) {
     str = str.substring(0, i + 1);
     break;
    }
   }
   return str;
  });
 
  var r, v = document.getElementById('theinput').value;
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
全正则
r = v.trimReg();
pending…
半正则
r = v.trimSemiReg()
pending…
native
r = v.trim()
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