Testing if a string is blank
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
With Native trimRight (if available) |
|
pending… |
Without Native |
|
pending… |
With Native Trim |
|
pending… |
Optimized |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments