Actually look at the source code of jquery, find each code is very simple, but why the performance and the original for loop dozens of times times difference?
The core code of each jquery
for (; i < length; i++) { value = Callback.call (Obj[i], I, obj[i]); if (value = = = False) {break ; } }
It's easy to look at, 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) {The judgment break is removed; }*/}} function Each2 (obj, callback) {var i = 0; var length = Obj.length for (; i < length; i++) {value = Callback (i, obj[i]);/* Remove call*/ if (value = = = False) {break; }}} 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))); }
Running the test, it was found that the first and second differences are not very large, which indicates that the performance difference due to the break is very small,
But the second and third, the fourth deviation is more than one, and the second and the third is the only difference is called call, it appears that calls will cause performance loss, because call will switch the context, of course, the jquery of each slow there are other reasons, it also called in the loop other methods, Call is just one reason.
So it can be said that call, and apply are JS in the comparison of the performance of the method, in strict performance requirements, it is recommended to use less.
Front-end performance optimizations: Why is jquery a lot slower than the native for loop?