String.fromCharCode vs UnicodeMapArray

ベンチマーク

by polygonplanet

HTML

ループ回数: <select id="max">
    <option value="1">1</option>
    <option value="10">10</option>
    <option value="100">100</option>
    <option value="1000">1000</option>
    <option value="10000">10000</option>
</select>
<hr>
<button type="button" id="execute">execute</button>
<hr>
<div id="cmp"></div>
<div>String.fromCharCode: <div id="res1"></div></div>
<div>Unicode map: <div id="res2"></div></div>

JavaScript

var byFromCharCode = function(c) {
    return String.fromCharCode(c);
};

var byUnicodeMap = (function() {
    var maps = [];
    for (var i = 0; i <= 0xFFFF; i++) {
        maps[i] = String.fromCharCode(i);
    }
    return function(c) {
        return maps[c & 0xFFFF];
    };
}());

$('#execute').click(function() {
    var that = $(this), org = that.text();
    that.text('実行中').attr({disabled : true});
    setTimeout(function() {
        exe();
        that.text(org).removeAttr('disabled');
    }, 10);
});

function exe() {
    var max = $('#max').val() - 0;
    
    // String.fromCharCode
    var time1 = +new Date;
    for (var n1 = 0; n1 < max; n1++) {
        var res1 = '';
        for (var i = 0; i <= 0xFFFF; i++) {
            res1 += byFromCharCode(i);
        }
    }
    time1 = +new Date - time1;
    
    // UnicodeMapArray
    var time2 = +new Date;
    for (var n2 = 0; n2 < max; n2++) {
        var res2 = '';
        for (var j = 0; j <= 0xFFFF; j++) {
            res2 += byUnicodeMap(j);
        }
    }
    time2 = +new Date - time2;
    
    $('#cmp').text( res1 === res2 );
    $('#res1').text(time1);
    $('#res2').text(time2);
}