regex vs charat

JavaScript performance comparison

Revision 3 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var addresses = ['test@test.test', 'test.test@test', 'test@test@test.test', '@test.etst', 't@est.test'];
   
    var regex = new RegExp(/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/);
   
    var whitespace = " \t\n\r";
   
    function charAtMethod(s)
    {
        if (isEmpty(s)) return false;
   
        if (isWhitespace(s)) return false;
   
        var i = 1;
        var sLength = s.length;
   
        while ((i < sLength) && (s.charAt(i) != "@"))
        { i++
        }
   
        if ((i >= sLength) || (s.charAt(i) != "@")) return false;
        else i += 2;
   
        while ((i < sLength) && (s.charAt(i) != "."))
        { i++
        }
        if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
        else return true;
    }
   
    function isEmpty(s)
    {
        return ((s == null) || (s.length == 0))
    }
   
    function isWhitespace(s)
    {
        var i;
   
        if (isEmpty(s)) return true;
        for (i = 0; i < s.length; i++)
        {
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
   
            if (whitespace.indexOf(c) == -1) return false;
        }
        return true;
    }
   
};
</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
regex
for (var x in addresses) {
  regex.test(addresses[x]);
}
pending…
charAt
for (var x in addresses) {
  charAtMethod(addresses[x]);
}
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