Measure javascript X jQuery performance
I am testing the difference between JS and jQuery.
The speed of this = document.getElementById('test'); - 0.048ms
document.getElementById('test'); - 0.048ms
The speed of this = $('#test'); - 0.333ms
$('#test'); - 0.333ms
Ok .. it's pretty obvious why pure JS is faster .. but, if I test this:
var test = function(selector) {
var a = document.getElementById(selector);
}
test('test');
SPEED: 12.270ms
What for? And how can jquery speed them up?
JQuery can't be faster than native getElementById method. You can test it yourself on jsperf .
Why? As jQuery has to add its own object handling to the list of objects returned by the selector $('#...')
.
EDIT
As suggested by sirrocco, I answer the question. The range of actions you specify is incorrect. You must have a time measurement error.
My test:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="jquery.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var start, end, i, time;
start = new Date().getTime();
for (i = 0; i < 500000; ++i) {
document.getElementById('test');
}
end = new Date().getTime();
time = end-start;
document.getElementById('res1').innerHTML = 'time = '+time+'ms';
start = new Date().getTime();
for (i = 0; i < 500000; ++i) {
$('#test');
}
end = new Date().getTime();
time = end-start;
document.getElementById('res2').innerHTML = 'time = '+time+'ms';
start = new Date().getTime();
for (i = 0; i < 500000; ++i) {
var test = function(selector) { var a = document.getElementById(selector); };
test('test');
}
end = new Date().getTime();
time = end-start;
document.getElementById('res3').innerHTML = 'time = '+time+'ms';
});
</script>
</head>
<body>
<pre>document.getElementById('test');</pre> <span id="res1">result</span></br>
</br>
<pre>$('#test');</pre> <span id="res2">result</span></br>
</br>
<pre> var test = function(selector) {
var a = document.getElementById(selector);
}
test('test');</pre> <span id="res3">result</span></br>
<span id="test">The element to find</span>
</body>
</html>
It's not the prettiest code in the world, but the addition of features changes the way browsers are optimized. Results on Corei7 + FF31:
document.getElementById('test');
time = 2ms
$('#test');
time = 680ms
var test = function(selector) {
var a = document.getElementById(selector);
}
test('test');
time = 33ms
In order of magnitude, you did not mention. But there is a difference between calling your own method directly and calling a function that calls your own method.
Why? As I said before, for jQuery it has to add its own object handling. And for your test with a function, there is time to create a new function object and to call it.
source to share