This article mainly introduces the reasons why jQuery's Each is much slower than JS's native for loop Performance. If you need it, you can refer to the jQuery source code and find that the each code is very simple, but why is the performance dozens of times different from that of the native for loop?
Core code of jQuery's each
for (; i < length; i++) { value = callback.call(obj[i], i, obj[i]); if (value === false) { break; } }
It looks simple, but why is it 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) {removed break;} */} 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]);/* Self-written 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 ("1 Test" + (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 ("2 Test" + (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 ("3 Test" + (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 ("4 Test" + (date12-date1 )));}
Run the test and find that the difference between the first and the second is not very large, which indicates that the performance difference caused by the break judgment is very small, but the second and third, the fourth deviation is more than doubled, and the second and third difference is that the call is called. It seems that the call will cause performance loss because the call will switch the context, of course, there are other reasons for jQuery's slow each. It also calls other methods in the loop. call is only one reason.
Therefore, call, and apply are both performance-consuming methods in js. We recommend that you use them less when the performance requirements are strict.
The following code shows the comparison of jquery's each and js native for loop Performance.
For and each performance comparison