luhn

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    valid = "4242424242424242"
    invalid = "4242424242424241"
   
   
    // http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#JavaScript
    function luhn10(a,b,c,d,e) {
      for(d = +a[b = a.length-1], e=0; b--;)
        c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;
      return !(d%10)
    };
   
    //https://gist.github.com/ShirtlessKirk/2134376
    function luhnjs(c){for(var d=c.length,b=0,e=[[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]],a=0;d--;)a+=e[b][parseInt(c.charAt(d),10)],b^=1;return 0===a%10&&0<a};
   
    function checkluhn(luhn) {
            var ca, sum = 0, mul = 0;
            var len = luhn.length;
   
            while (len--) {
                ca = parseInt(luhn.charAt(len),10) << mul;
                sum += ca - (ca>9)*9; // sum += ca - (-(ca>9))|9
                // 1 <--> 0 toggle.
                mul ^= 1; // mul = 1 - mul;
                }
   
                return (sum % 10 === 0) && (sum > 0);
    }
};
</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
luhn.js
luhnjs(invalid)
luhnjs(valid)
pending…
rosetta
luhn10(invalid)
luhn10(valid)
pending…
CheckLuhn
checkluhn(valid)
checkluhn(invalid)
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