Testing if a string is blank

JavaScript performance comparison

Test case created by Robert

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var hasTrimRight = !! String.prototype.trimRight;
   
    function isBlankWithNativeTrimRight(string) {
      if (string === '') {
        return true;
      }
   
      // I assume this is faster, if it exists
      if (hasTrimRight && string.trimRight() === '') {
        return true;
      }
   
      // matches most space or empty characters (including some unicode whitespace characters)
      if (string.match(/^[ \t\r\n\u00A0\u2000-\u200B]+$/)) {
        return true;
      }
   
      return false;
    }
   
    var hasTrim = !! String.prototype.trim;
   
    function isBlankWithNativeTrim(string) {
      if (string === '') {
        return true;
      }
   
      // I assume this is faster, if it exists
      if (hasTrim && string.trim() === '') {
        return true;
      }
   
      // matches most space or empty characters (including some unicode whitespace characters)
      if (string.match(/^[ \t\r\n\u00A0\u2000-\u200B]+$/)) {
        return true;
      }
   
      return false;
    }
   
    function isBlankNoNative(string) {
      if (string === '') {
        return true;
      }
   
      if (string.match(/^[ \t\r\n\u00A0\u2000-\u200B]+$/)) {
        return true;
      }
   
      return false;
    }
   
    var strIsBlank = (function() {
      if ( !! String.prototype.trim) {
        return function(string) {
          if (string === '' || string.trim() === '') {
            return true;
          }
   
          return false;
        };
      }
   
      return function(string) {
        // matches most space or empty characters (including some unicode whitespace characters)
        if (string === '' || string.match(/^[ \t\r\n\u00A0\u2000-\u200B]+$/)) {
          return true;
        }
   
        return false;
      };
    })();
};
</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
With Native trimRight (if available)
isBlankWithNativeTrimRight('');
isBlankWithNativeTrimRight(' ');
isBlankWithNativeTrimRight('    '); // includes unicode &nbsp; character
pending…
Without Native
isBlankNoNative('');
isBlankNoNative(' ');
isBlankNoNative('    '); // includes unicode &nbsp; character
pending…
With Native Trim
isBlankWithNativeTrim('');
isBlankWithNativeTrim(' ');
isBlankWithNativeTrim('    ');
pending…
Optimized
strIsBlank('');
strIsBlank(' ');
strIsBlank('    ');
pending…

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

Compare results of other browsers

0 comments

Add a comment