tags:

views:

45

answers:

1

This question is about javascript performance. Consider 3 examples for illustration:

function loadImgA() {
    new Image().src="http://example.com/image.gif"
}

function loadImgA1() {
    Image().src="http://example.com/image.gif"
}

function loadImgB() {
    var testImg = new Image();
    testImg.src="http://example.com/image.gif"
}

Now the point is I don't really need to manipulate the the image object after it was created, hence loadImgA(). The question is, what happens if nothing is assigned to the return value of the new Image() constructor - in that case I can actually skip the 'new' keyword as in loadImgA1()? Does the object then live outside the function or somehow affects memory usage? Other implications, differences? I reckon not, as no real instance was actually created?

To put this into perspective, I only need to get the http request for image through. No preloading or other advanced image manipulation. What would be the preferred method from the above?

A: 

Using Image() without the new keyword will throw an error (at least, it does in IE). In your examples loadImgA() and loadImgB() will have the same end result as nothing is returned from the function and no closure is created to make use of the testImg variable.

With regards to memory usage, new Image() is a shortcut for document.createElement("img"). When a DOM element is created in the scope of a function and not added to the document, when all closures are complete the element should be marked for garbage collection and removed from memory. An instance is actually created, just not added to the DOM so it is destroyed when no longer in use.

The only real problem I could see arising from this is that when the image object is destroy, any current http requests on them might be destroyed. If that's the case, you might need to use the onload or onerror event handler to clean up after the image is loaded or if there is a problem.

Andy E
Thanks Andy. I would think the same Image() being a shortcut for w3c document.createElement("img") but there are some suggestions why it may not be exact 1:1: http://engineeredweb.com/blog/09/12/performance-comparison-documentcreateelementimg-vs-new-imageUsing Image() without the new keyword is indeed incorrect.The point on destorying http requests may be valid although I wasn't able to confirm.
@user276027: Thanks for the link, it was an interesting read.
Andy E