Quentin Roy
Quentin Roy

Reputation: 7887

Why DOMParser requires to be instantiated?

One of the preferred native methods to create DOM elements from a string a la jQuery is to use the new DOMParser class. This example is extracted from the MDN:

var parser = new DOMParser();
var doc = parser.parseFromString(aStr, "text/xml");

I wonder if there is any particular reason to the extra-step that requires to instantiate a parser before parsing a string. I.e. why can't we just do something like parseFromString(aStr, "text/xml"); ?

The parser object looks superfluous. DOMParser constructor doesn't even have any arguments and its instances doesn't have any method other than parseFromString.

Upvotes: 5

Views: 868

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 175088

If I remember correctly, putting up a DOM parser ready to parse text is an expensive operation (memory-wise), so in order to save the memory hit from setting up a DOM parser for each page/tab you visit, the browser will clear the memory from the initial DOM parser it instantiates (to parse the document's source), and unless you instantiate it again, that memory is clear.

If you want, you can use the profiler tool in your favorite browser to see how memory changes before and after instantiating the DOM parser.

Upvotes: 2

Related Questions