Created
November 20, 2012 07:32
-
-
Save ymkjp/4116582 to your computer and use it in GitHub Desktop.
Performance: NodeList vs. Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Performance race</title> | |
</head> | |
<body> | |
<h1>Performance race: NodeList vs. Array</h1> | |
<p>Check the console.</p> | |
<div> | |
<!-- write 1000 <span> tags --> | |
</div> | |
<script type="text/javascript"> | |
var elems, len; | |
// Entry No. 1 | |
console.time('Use NodeList as no cahges & get length everytime'); | |
elems = document.getElementsByTagName('span'); | |
for (var i = 0; i < 1000; i++) { | |
for (var j = 0; j < elems.length; j++) { | |
elems[j]; | |
} | |
} | |
console.timeEnd('Use NodeList as no cahges & get length everytime'); | |
// Entry No. 2 | |
console.time('Use NodeList as no cahges'); | |
elems = document.getElementsByTagName('span'); | |
len = elems.length; | |
for (var i = 0; i < 1000; i++) { | |
for (var j = 0; j < len; j++) { | |
elems[j]; | |
} | |
} | |
console.timeEnd('Use NodeList as no cahges'); | |
// Entry No. 3 | |
console.time('Convert to Array & get length everytime'); | |
// Not supported: IE8 and older versions // => error | |
elems = Array.prototype.slice.call(document.getElementsByTagName('span')); | |
for (var i = 0; i < 1000; i++) { | |
for (var j = 0; j < elems.length; j++) { | |
elems[j]; | |
} | |
} | |
console.timeEnd('Convert to Array & get length everytime'); | |
// Entry No. 4 | |
console.time('Convert to Array'); | |
// Not supported: IE8 and older versions // => error | |
elems = Array.prototype.slice.call(document.getElementsByTagName('span')); | |
len = elems.length; | |
for (var i = 0; i < 1000; i++) { | |
for (var j = 0; j < len; j++) { | |
elems[j]; | |
} | |
} | |
console.timeEnd('Convert to Array'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment