jquery-append-options-to-select

JavaScript performance comparison

Test case created by Dan Manastireanu

Info

The goal is to populate a select with the options available in an array, and one selected value.

Read more about jQuery append with an array as first argument

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var options = [1, 3, 4, 6, 12],
        selected = 3,
        $select = $('<select></select>');
};

Benchmark.prototype.teardown = function() {
    $select = $('<select></select>');
};
</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
each-append-to
$.each(options, function() {
  $('<option value="' + this + '">' + this + '</option>').attr('selected', this == selected).appendTo($select);
});
pending…
each-append
$.each(options, function() {
  $select.append($('<option value="' + this + '">' + this + '</option>').attr('selected', this == selected));
});
pending…
each-append-string
$.each(options, function() {
  var o = '<option value="' + this + '"' + (this == selected ? ' selected="selected"' : '') + '>' + this + '</option>';
  $select.append(o);
});
pending…
append-map-jq
$select.append($.map(options, function(o) {
  return $('<option value="' + o + '">' + o + '</option>').attr('selected', o === selected)[0];
}));
pending…
append-map-string-join
$select.append($.map(options, function(o) {
  return '<option value="' + o + '"' + (o === selected ? ' selected="selected"' : '') + '>' + o + '</option>';
}).join(''));
pending…
append-apply-map-string
$select.append.apply($select, $.map(options, function(o) {
  return '<option value="' + o + '"' + (o === selected ? ' selected="selected"' : '') + '>' + o + '</option>';
}));
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