Option.add vs Element.appendChild

JavaScript performance comparison

Test case created by ThinkingStiff

Info

Stackoverflow - http://stackoverflow.com/q/8377498/918414

Preparation code

<select name="mois" id="mois"></select>
 
<script>
Benchmark.prototype.setup = function() {
        var month = [
            "Janvier","Février","Mars","Avril","Mai","Juin",
            "Juillet","Aout","Septembre","Octobre","Novembre","Décembre"
            ];
   
};

Benchmark.prototype.teardown = function() {
    document.getElementById( 'mois' ).innerHTML = '';
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Option.add
    var month = [
        "Janvier","Février","Mars","Avril","Mai","Juin",
        "Juillet","Aout","Septembre","Octobre","Novembre","Décembre"
        ],  
        now = new Date(),
        nowMonth = now.getMonth(),
        currentMonth = document.createElement( 'option' ),
        nextMonth = document.createElement( 'option' ),
        mois = document.getElementById( 'mois' );

    currentMonth.value = nowMonth;
    currentMonth.text = month[nowMonth];
    mois.add( currentMonth );

    now.setMonth( nowMonth + 1 );
    nextMonth.value = now.getMonth();
    nextMonth.text = month[now.getMonth()];
    mois.add( nextMonth );
 
pending…
Element.appendChild
var d = new Date(),
    lastMonth = month.length - 1,
    thisMonth = d.getMonth(),
    nextMonth = thisMonth === lastMonth ? 0 : thisMonth + 1;

var opt = document.createElement('option'),
   optTxt = document.createTextNode(month[thisMonth]);
opt.value = thisMonth;
opt.appendChild(optTxt);
document.getElementById('mois').appendChild(opt);

opt = document.createElement('option');
optTxt = document.createTextNode(month[nextMonth]);
opt.value = nextMonth;
opt.appendChild(optTxt);
document.getElementById('mois').appendChild(opt);
 
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