Ternary vs if using JQuery

JavaScript performance comparison

Test case created by Sandy

Info

Using a ternary operator to select a property of a JQuery object vs doing it separately with an if statement.

Preparation code

<div id="theAppContainer"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    var s, u;
};
</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
Ternary, s > u
s = 2;
u = 1;

$("#theAppContainer")[s > u ? "addClass" : "removeClass"]("something");
pending…
If, s > u
s = 2;
u = 1;

var container = $('#theAppContainer');

if(s > u) {
    container.addClass('something');
} else {
    container.removeClass('something');
}
pending…
Ternary, s < u
s = 1;
u = 2;

$("#theAppContainer")[s > u ? "addClass" : "removeClass"]("something");
pending…
If, s < u
s = 1;
u = 2;

var container = $('#theAppContainer');

if(s > u) {
    container.addClass('something');
} else {
    container.removeClass('something');
}
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