Trim vs Strip

JavaScript performance comparison

Revision 2 of this test case created by Andrew Wilson

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.0.2/underscore.string.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  var strip = function(string, characters) {

      'use strict';
      if(!characters) {
          if(typeof String.prototype.trim !== undefined) {
              // Simply use the String.trim as a default
              return String.prototype.trim.call(string);
           } else {
              // set characters to whitespaces
              characters = "\s\uFEFF\xA0";
           }
      }
      // Characters is set at this point forward
      // Validate characters just in case there are invalid usages
      var escaped = characters.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
      
      var target = new RegExp('^[' + escaped + ']+|[' + escaped + ']+$');
      
      // Remove the characters from the beginning of the string
      string = string.replace(target, '');
  };
  

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Trimming with strip
var trimmed = 'NothingToTrim';
strip(trimmed);
pending…
Trimming with many spaces
var trimmed = '          10 Left 20 right                  ';
trimmed.trim();
pending…
Stripping with many spaces
var trimmed = '          10 Left 20 right                  ';
strip(trimmed);
pending…
Stripping characters
var trimmed = 'aaaaaaaaaa10 Left 20 rightaaaaaaaaaaaaaaaaaaaa';
strip(trimmed,'a');
pending…
Stripping multiple chars
var trimmed = 'a b a a a a 10 Left 20 right        b  a b      ';
strip(trimmed, 'ab ');
pending…
Underscore.string trimming
var trimmed = 'a b a a a a 10 Left 20 right        b  a b      '; s.trim(trimmed, 'ab ');
pending…
Trimming with trim
var trimmed = 'NothingToTrim';
trimmed.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.

0 Comments