Monday, December 22, 2008

When to use SAX and DOM?

This question doesn’t have any straight or fix answer because it really depends upon the situation. Different parameters (memory, speed etc) have to be taken into consideration to make this decision. We go through some of points that will be helpful in making the decision which API should be used in which situation.
  • DOM is memory intensive while SAX is not, because DOM creates a Document object in memory using a tree data structure while SAX does not create any such default object in memory rather uses custom object which makes SAX less memory intense.
  • DOM is slower than SAX for the same reason as of memory.
  • DOM provides a random access to the XML contents of the document having them in memory while SAX provides sequential access to the contents as it has access to one part of the document at a time.
  • DOM has an edge over SAX that it provides ability to modify the document which is not the case with SAX. This implies that if client application is concerned about the location of different elements within the document (may be to modify it) then DOM is the option, however, if it’s concerned with individual elements then SAX is the right option.
  • From a parser’s point of view, there is nothing much to do for a parser for SAX. There are few interfaces to be implemented for SAX for parser while this is not the case with DOM. Most of the parsers support both of these models.
Based on these points, you can have some idea which model is the most suitable to your needs!!

1 comment:

Anonymous said...

Have you looked at VTD-XML? it is 10x faster and 5x more memory efficent tha DOM4J or JDOM

http://vtd-xml.sf.net