In fact, looking at the source code of jquery, found that each of the code is very simple, but why the performance and the original for loop dozens of times times the difference?
The core code for each of jquery
for (; i < length; i++) {
value = Callback.call (Obj[i], I, obj[i]);
if (value = = False) {break
;
}
}
It looks simple, but why is it so much slower?
Write the test code as follows:
var length=300000;
function Getarr () {var t = [];
for (var i = 0; i < length; i++) {t[i] = i;
} return t;
function Each1 (obj, callback) {var i = 0;
var length = Obj.length for (; i < length; i++) {value = Callback (i, obj[i]);
/* if (value = = False) {Remove the judgment break;
}*/}} function Each2 (obj, callback) {var i = 0; var length = Obj.length for (; i < length; i++) {value = Callback (i, obj[i]);/* Removed call*/if (value = = False) {BR
Eak
}} function Each3 (obj, callback) {var i = 0; var length = Obj.length for (; i < length; i++) {value = Callback.call (Obj[i], I, obj[i]);//write your own call*/if (value = =
= False) {break;
}} function Test1 () {var t = Getarr ();
var date1 = new Date (). GetTime ();
var lengtharr = t.length;
var total = 0;
Each1 (t, function (i, n) {total = n;
});
var date12 = new Date (). GetTime ();
Console.log ("1Test" + ((date12-date1));
function Test2 () {var t = Getarr (); var date1 = new Date (). GetTime ();
var total = 0;
EACH2 (t, function (i, n) {total = n;
});
var date12 = new Date (). GetTime ();
Console.log ("2Test" + ((date12-date1));
function Test3 () {var t = Getarr ();
var date1 = new Date (). GetTime ();
var total = 0;
EACH3 (t, function (i, n) {total = n;
});
var date12 = new Date (). GetTime ();
Console.log ("3Test" + ((date12-date1));
function Test4 () {var t = Getarr ();
var date1 = new Date (). GetTime ();
var total = 0;
$.each (t, function (i, n) {total = n;
});
var date12 = new Date (). GetTime ();
Console.log ("4Test" + ((date12-date1)); }
Run the test, found that the first and second difference is not very large, this shows that because of the difference in performance caused by the break, but the second and third, the fourth deviation is more than one, and the second and third the only difference is called call, it seems that calls can cause loss of performance, Because call switches the context, of course, there are other reasons for each slow of jquery, and it calls other methods in the loop, which is just one reason.
So it can be said that call, and apply are compared to the consumption of JS in the performance of the method, when the performance requirements of strict, less recommended.
The following is a piece of code to look at jquery each and JS native for loop performance comparison