0

I'm preparing to take a JavaScript test, and came upon this post: http://www.javascriptkit.com/javatutors/efficientjs.shtml

The gist is that this:

<script type="text/javascript">
for (var i=0;i<document.images.length;i++)
    document.images[i].src="blank.gif"
</script>

is not as efficient as this:

<script type="text/javascript">
var theimages=document.images
for (var i=0;i<theimages.length;i++)
    theimages[i].src="blank.gif"
</script>

because the object is 'cached' in a user defined variable.

Is this still the situation with modern JavaScript engines?

Ed Pfromer
  • 46
  • 4
  • Your tutorial seems to be badly outdated. I've seen someone using `document.images` collection last in 1999, at the time of DHTML, which is actually also mentioned in the text. Instead of the object itself, you should cache the length property. "Caching" an object means that you should store a reference to it instead of re-creating it every time you need it. – Teemu Mar 11 '20 at 18:37
  • Thanks @Teemu. Yes, the article is ancient and I found it hard to believe. Indeed, after I set up a test environment and measured with console.time() and .timeEnd() I couldn't find any substantive differences between the two approaches. – Ed Pfromer Mar 11 '20 at 20:35
  • Considering `.images` is a live collection (it's updated every time when it's retrieved), caching the values of the collection improves the performance. That means, that you'd create an array of the values of the collection, either by creating it with `Array.from(document.images)`, or directly with `document.querySelectorAll('img')`. If the document is huge or there are a ton of images, this makes the loop a bit faster. In smaller documents this is a border-case of micro optimization. – Teemu Mar 12 '20 at 05:39

0 Answers0