JSFiddle - React, Tailwind, and code Playground
HTML
<h2>$.each() vs $().each() vs plain JS value alteration vs for() loop</h2>
<ul id="testArea">
<li data-test="someValue0">Item here 1</li>
<li data-test="someValue1">Item here 2</li>
<li data-test="someValue2">Item here 3</li>
<li data-test="someValue3">Item here 4</li>
<li data-test="someValue4">Item here 5</li>
<li data-test="someValue5">Item here 6</li>
<li data-test="someValue6">Item here 7</li>
<li data-test="someValue7">Item here 8</li>
</ul>
<table id="results">
<tr>
<th>Function Desc:</th>
<th>Execution Time:</th>
</tr>
</table>
CSS
body { padding:20px; color:#242424; font-family: "Lucida Grande", Tahoma, "Trebuchet MS"; }
h2 { background:#5279a4; color:#fff; padding:5px; }
div { padding:5px; }
ul { padding:25px; font-size:10px; }
table th, table td { padding:3px; }
table td { font-size:10px; font-weight:bold; }
table td.time { padding-left:50px; font-color:#5279a4; }
JavaScript
// mcpDESIGNS
var _unitTest = function (func, funcArgs, funcDesc) {
//NOTE: Tests a functions run time by looping through it 50000 times.
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
func.apply(null, funcArgs);
}
var end = new Date().getTime(),
time = end - start;
$('#results').append('<tr><td>' + funcDesc + '</td><td class="time">' + time);
};
var _testArea = $('#testArea li');
var func1 = function () {
_testArea.each(function (i, el) {
$(this).attr('data-newAttr', 'counter' + i);
});
};
var func2 = function () {
$.each(_testArea, function (i, el) {
$(this).attr('data-newAttr', 'counter' + i);
});
};
// $(this) attribute set
_unitTest(func1, null, '_testArea.each() + $(this)');
_unitTest(func2, null, '$.each() + $(this)');
var func3 = function () {
_testArea.each(function (i, el) {
el.setAttribute('data-newAttr', 'counter' + i);
});
};
var func4 = function () {
$.each(_testArea, function (i, el) {
el.setAttribute('data-newAttr', 'counter' + i);
});
};
// raw JS - use of element
_unitTest(func3, null, '_testArea.each() + el(plain JS)');
_unitTest(func4, null, '$.each() + el(plain JS)');
var func5 = function () {
for (var i = 0, len = _testArea.length; i < len; i++) {
_testArea[i].setAttribute('data-newAttr', 'counter' + i);
}
};
_unitTest(func5, null, 'for() loop + plainJS[0] iteration');