predefined vs new query

JavaScript performance comparison

Revision 2 of this test case created and last updated

Info

see if it is quick to pre define your jquery objects in certain instances or not.

Preparation code

<div id="box">
  <h1>
    hello
  </h1>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

Preparation code output

hello

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
unique call
$("#box").find("h1");
$("#box").find("h1").text("go1");
$("#box").find("h1").text("go2");
$("#box").find("h1").text("go3");
pending…
predefined call
var theBox = $("#box").find("h1");
theBox.text("go1");
theBox.text("go2");
theBox.text("go3");
pending…
extracted function 1
var theBox = $("#box").find("h1");

function update(string) {
  theBox.text(string);
}

update("go1");
update("go2");
update("go3");
pending…
extracted function 2
var theBox = $("#box").find("h1");

var update = function(string) {
  theBox.text(string);
}

update("go1");
update("go2");
update("go3");
pending…
extracted function 3
var theBox = $("#box").find("h1");

function update(obj,string) {
  obj.text(string);
}

update(theBox,"go1");
update(theBox,"go2");
update(theBox,"go3");
pending…
extracted function 4
var theBox = $("#box").find("h1");

var update = function(obj,string) {
  obj.text(string);
}

update(theBox,"go1");
update(theBox,"go2");
update(theBox,"go3");
pending…
extracted function 5
function update(string) {
  $("#box").find("h1").text(string);
}

update("go1");
update("go2");
update("go3");
pending…
extracted function 6
var theBox = $("#box").find("h1");

var update = function(obj,string) {
  obj.text(string);
}

update(theBox,"go1");
update(theBox,"go2");
update(theBox,"go3");
pending…
extracted function 7 - what jquery does when no ones looking.
var theBox = document.getElementById("box").getElementsByTagName("h1")[0].childNodes[0].nodeValue;

var update = function(string) {
  theBox = string;
}

update("go1");
update("go2");
update("go3");
pending…
what jquery does when no ones looking.
var theBox = document.getElementById("box").getElementsByTagName("h1")[0].childNodes[0].nodeValue;

theBox = "go1";
theBox = "go2";
theBox = "go3";
 
pending…
hybrid
var theBox = document.getElementById("box").getElementsByTagName("h1")[0];

var update = function(string) {
  $(theBox).text(string);
}

update("go1");
update("go2");
update("go3");
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