XML unmarshalling benchmark in Java: JAXB vs STax vs Woodstox
Join the DZone community and get the full member experience.
Join For Freetowards the end of last week i started thinking how to deal with large amounts of xml data in a resource-friendly way.the main problem that i wanted to solve was how to process large xml files in chunks while at the same time providing upstream/downstream systems with some data to process.
of course i've been using jaxb technology for few years now; the main advantage of using jaxb is the quick time-to-market; if one possesses an xml schema, there are tools out there to auto-generate the corresponding java domain model classes automatically (eclipse indigo, maven jaxb plugins in various sauces, ant tasks, to name a few). the jaxb api then offers a marshaller and an unmarshaller to write/read xml data, mapping the java domain model.
when thinking of jaxb as solution for my problem i suddendlly realised that jaxb keeps the whole objectification of the xml schema in memory, so the obvious question was: "how would our infrastructure cope with large xml files (e.g. in my case with a number of elements > 100,000) if we were to use jaxb?". i could have simply produced a large xml file, then a client for it and find out about memory consumption.
as one probably knows there are mainly two approaches to processing xml data in java: dom and sax. with dom, the xml document is represented into memory as a tree; dom is useful if one needs cherry-pick access to the tree nodes or if one needs to write brief xml documents. on the other side of the spectrum there is sax, an event-driven technology, where the whole document is parsed one xml element at the time, and for each xml significative event, callbacks are "pushed" to a java client which then deals with them (such as start_document, start_element, end_element, etc). since sax does not bring the whole document into memory but it applies a cursor like approach to xml processing it does not consume huge amounts of memory. the drawback with sax is that it processes the whole document start to finish; this might not be necessarily what one wants for large xml documents. in my scenario, for instance, i'd like to be able to pass to downstream systems xml elements as they are available, but at the same time maybe i'd like to pass only 100 elements at the time, implementing some sort of pagination solution. dom seems too demanding from a memory-consumption point of view, whereas sax seems to coarse-grained for my needs.
i remembered reading something about stax, a java technology which offered a middle ground between the capability to pull xml elements (as opposed to pushing xml elements, e.g. sax) while being ram-friendly. i then looked into the technology and decided that stax was probably the compromise i was looking for; however i wanted to keep the easy programming model offered by jaxb, so i really needed a combination of the two. while investigating stax, i came across woodstox; this open source project promises to be a faster xml parser than many othrers, so i decided to include it in my benchmark as well. i now had all elements to create a benchmark to give me memory consumption and processing speed metrics when processing large xml documents.
the benchmark plan
in order to create a benchmark i needed to do the following:
- create an xml schema which defined my domain model. this would be the input for jaxb to create the java domain model
- create three large xml files representing the model, with 10,000 / 100,000 / 1,000,000 elements respectively
- have a pure jaxb client which would unmarshall the large xml files completely in memory
- have a stax/jaxb client which would combine the low-memory consumption of sax technologies with the ease of programming model offered by jaxb
- have a woodstox/jaxb client with the same characteristics of the stax/jaxb client (in few words i just wanted to change the underlying parser and see if i could obtain any performance boost)
- record both memory consumption and speed of processing (e.g. how quickly would each solution make xml chunks available in memory as jaxb domain model classes)
- make the results available graphically, since, as we know, one picture tells one thousands words.
the domain model xml schema
<?xml version="1.0" encoding="utf-8"?> <schema xmlns="http://www.w3.org/2001/xmlschema" targetnamespace="http://uk.co.jemos.integration.xml/large-file" xmlns:tns="http://uk.co.jemos.integration.xml/large-file" elementformdefault="qualified"> <complextype name="persontype"> <sequence> <element name="firstname" type="string"></element> <element name="lastname" type="string"></element> <element name="address1" type="string"></element> <element name="address2" type="string"></element> <element name="postcode" type="string"></element> <element name="city" type="string"></element> <element name="country" type="string"></element> </sequence> <attribute name="active" type="boolean" use="required" /> </complextype> <complextype name="personstype"> <sequence> <element name="person" type="tns:persontype" maxoccurs="unbounded" minoccurs="1"></element> </sequence> </complextype> <element name="persons" type="tns:personstype"> </element> </schema>
i decided for a relatively easy domain model, with xml elements representing people, with their names and addresses. i also wanted to record whether a person was active.
using jaxb to create the java model
i am a fan of maven and use it as my default tool to build systems. this is the pom i defined for this little benchmark:
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>uk.co.jemos.tests.xml</groupid> <artifactid>large-xml-parser</artifactid> <version>1.0.0-snapshot</version> <packaging>jar</packaging> <name>large-xml-parser</name> <url>http://www.jemos.co.uk</url> <properties> <project.build.sourceencoding>utf-8</project.build.sourceencoding> </properties> <build> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupid>org.jvnet.jaxb2.maven2</groupid> <artifactid>maven-jaxb2-plugin</artifactid> <version>0.7.5</version> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <schemadirectory>${basedir}/src/main/resources</schemadirectory> <includeschemas> <includeschema>**/*.xsd</includeschema> </includeschemas> <extension>true</extension> <args> <arg>-enableintrospection</arg> <arg>-xtostring</arg> <arg>-xequals</arg> <arg>-xhashcode</arg> </args> <removeoldoutput>true</removeoldoutput> <verbose>true</verbose> <plugins> <plugin> <groupid>org.jvnet.jaxb2_commons</groupid> <artifactid>jaxb2-basics</artifactid> <version>0.6.1</version> </plugin> </plugins> </configuration> </plugin> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-jar-plugin</artifactid> <version>2.3.1</version> <configuration> <archive> <manifest> <addclasspath>true</addclasspath> <mainclass>uk.co.jemos.tests.xml.xmlpullbenchmarker</mainclass> </manifest> </archive> </configuration> </plugin> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-assembly-plugin</artifactid> <version>2.2</version> <configuration> <outputdirectory>${project.build.directory}/site/downloads</outputdirectory> <descriptors> <descriptor>src/main/assembly/project.xml</descriptor> <descriptor>src/main/assembly/bin.xml</descriptor> </descriptors> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.5</version> <scope>test</scope> </dependency> <dependency> <groupid>uk.co.jemos.podam</groupid> <artifactid>podam</artifactid> <version>2.3.11.release</version> </dependency> <dependency> <groupid>commons-io</groupid> <artifactid>commons-io</artifactid> <version>2.0.1</version> </dependency> <!-- xml binding stuff --> <dependency> <groupid>com.sun.xml.bind</groupid> <artifactid>jaxb-impl</artifactid> <version>2.1.3</version> </dependency> <dependency> <groupid>org.jvnet.jaxb2_commons</groupid> <artifactid>jaxb2-basics-runtime</artifactid> <version>0.6.0</version> </dependency> <dependency> <groupid>org.codehaus.woodstox</groupid> <artifactid>stax2-api</artifactid> <version>3.0.3</version> </dependency> </dependencies> </project>
just few things to notice about this pom.xml.
- i use java 6, since starting from version 6, java contains all the xml libraries for jaxb, dom, sax and stax.
- to auto-generate the domain model classes from the xsd schema, i used the excellent maven-jaxb2-plugin, which allows, amongst other things, to obtain pojos with tostring, equals and hashcode support.
i have also declared the jar plugin, to create an executable jar for the benchmark and the assembly plugin to distribute an executable version of the benchmark. the code for the benchmark is attached to this post, so if you want to build it and run it yourself, just unzip the project file, open a command line and run:
$ mvn clean install assembly:assembly
this command will place *-bin.* files into the folder target/site/downloads. unzip the one of your preference and to run the benchmark use (-dcreate.xml=true will generate the xml files. don't pass it if you have these files already, e.g. after the first run):
$ java -jar -dcreate.xml=true large-xml-parser-1.0.0-snapshot.jar
creating the test data
to create the test data, i used podam , a java tool to auto-fill pojos and javabeans with data. the code is as simple as:
jaxbcontext context = jaxbcontext .newinstance("xml.integration.jemos.co.uk.large_file"); marshaller marshaller = context.createmarshaller(); marshaller.setproperty(marshaller.jaxb_formatted_output, boolean.true); marshaller.setproperty(marshaller.jaxb_encoding, "utf-8"); personstype personstype = new objectfactory().createpersonstype(); list<persontype> persons = personstype.getperson(); podamfactory factory = new podamfactoryimpl(); for (int i = 0; i < nbrelements; i++) { persons.add(factory.manufacturepojo(persontype.class)); } jaxbelement<personstype> towrite = new objectfactory() .createpersons(personstype); file file = new file(filename); bufferedoutputstream bos = new bufferedoutputstream( new fileoutputstream(file), 4096); try { marshaller.marshal(towrite, bos); bos.flush(); } finally { ioutils.closequietly(bos); }
the xmlpullbenchmarker generates three large xml files under ~/xml-benchmark:
- large-person-10000.xml (approx 3m)
- large-person-100000.xml (approx 30m)
- large-person-1000000.xml (approx 300m)
each file looks like the following:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <persons xmlns="http://uk.co.jemos.integration.xml/large-file"> <person active="false"> <firstname>ult6yn0d7l</firstname> <lastname>u8djoutlk2</lastname> <address1>dxwlpow6x3</address1> <address2>o4ggvximo7</address2> <postcode>io7kuz0xmz</postcode> <city>lmiy1uqkxs</city> <country>zhtukbtwti</country> </person> <person active="false"> <firstname>gbc7kex9tn</firstname> <lastname>kxmwnlprep</lastname> <address1>9bibs1m5gr</address1> <address2>hmtqpxjcpw</address2> <postcode>bhpf1rrldm</postcode> <city>ydjjillyrw</city> <country>xgstdjcfjc</country> </person> [..etc] </persons>
each file contains 10,000 / 100,000 / 1,000,000 <person> elements.
the running environments
i tried the benchmarker on three different environments:
- ubuntu 10, 64-bit running as virtual machine on a windows 7 ultimate, with cpu i5, 750 @2.67ghz and 2.66ghz, 8gb ram of which 4gb dedicated to the vm. jvm: 1.6.0_25, hotspot
- windows 7 ultimate , hosting the above vm, therefore with same processor. jvm, 1.6.0_24, hotspot
- ubuntu 10, 32-bit , 3gb ram, dual core. jvm, 1.6.0_24, openjdk
the xml unmarshalling
to unmarshall the code i used three different strategies:
- pure jaxb
- stax + jaxb
- woodstox + jaxb
pure jaxb unmarshalling
the code which i used to unmarshall the large xml files using jaxb follows:
private void readlargefilewithjaxb(file file, int nbrrecords) throws exception { jaxbcontext ucontext = jaxbcontext .newinstance("xml.integration.jemos.co.uk.large_file"); unmarshaller unmarshaller = ucontext.createunmarshaller(); bufferedinputstream bis = new bufferedinputstream(new fileinputstream( file)); long start = system.currenttimemillis(); long memstart = runtime.getruntime().freememory(); long memend = 0l; try { jaxbelement<personstype> root = (jaxbelement<personstype>) unmarshaller .unmarshal(bis); root.getvalue().getperson().size(); memend = runtime.getruntime().freememory(); long end = system.currenttimemillis(); log.info("jaxb (" + nbrrecords + "): - total memory used: " + (memstart - memend)); log.info("jaxb (" + nbrrecords + "): time taken in ms: " + (end - start)); } finally { ioutils.closequietly(bis); } }
the code uses a one-liner to unmarshall each xml file:
jaxbelement<personstype> root = (jaxbelement<personstype>) unmarshaller .unmarshal(bis);
i also accessed the size of the underlying persontype collection to "touch" in memory data. btw, debugging the application showed that all 10,000 elements were indeed available in memory after this line of code.
jaxb + stax
with stax, i just had to use an xmlstreamreader, iterate through all <person> elements, and pass each in turn to jaxb to unmarshall it into a persontype domain model object. the code follows:
// set up a stax reader xmlinputfactory xmlif = xmlinputfactory.newinstance(); xmlstreamreader xmlr = xmlif .createxmlstreamreader(new filereader(file)); jaxbcontext ucontext = jaxbcontext.newinstance(persontype.class); unmarshaller unmarshaller = ucontext.createunmarshaller(); long start = system.currenttimemillis(); long memstart = runtime.getruntime().freememory(); long memend = 0l; try { xmlr.nexttag(); xmlr.require(xmlstreamconstants.start_element, null, "persons"); xmlr.nexttag(); while (xmlr.geteventtype() == xmlstreamconstants.start_element) { jaxbelement<persontype> pt = unmarshaller.unmarshal(xmlr, persontype.class); if (xmlr.geteventtype() == xmlstreamconstants.characters) { xmlr.next(); } } memend = runtime.getruntime().freememory(); long end = system.currenttimemillis(); log.info("stax - (" + nbrrecords + "): - total memory used: " + (memstart - memend)); log.info("stax - (" + nbrrecords + "): time taken in ms: " + (end - start)); } finally { xmlr.close(); } }
note that this time when creating the context, i had to specify that it was for the persontype object, and when invoking the jaxb unmarshalling i had to pass also the desired returned class type, with:
jaxbelement<persontype> pt = unmarshaller.unmarshal(xmlr,
persontype.class);
note that i don't to anything with the object, just create it, to keep the benchmark as truthful and possible by not introducing any unnecessary steps.
jaxb + woodstox
with woodstox, the approach is very similar to the one used with stax. in fact woodstox provides a stax2 compatible api, so all i had to do was to provide the correct factory and...bang! i had woodstox under the cover working.
private void readlargexmlwithfasterstax(file file, int nbrrecords) throws factoryconfigurationerror, xmlstreamexception, filenotfoundexception, jaxbexception { // set up a woodstox reader xmlinputfactory xmlif = xmlinputfactory2.newinstance(); xmlstreamreader xmlr = xmlif .createxmlstreamreader(new filereader(file)); jaxbcontext ucontext = jaxbcontext.newinstance(persontype.class); unmarshaller unmarshaller = ucontext.createunmarshaller(); long start = system.currenttimemillis(); long memstart = runtime.getruntime().freememory(); long memend = 0l; try { xmlr.nexttag(); xmlr.require(xmlstreamconstants.start_element, null, "persons"); xmlr.nexttag(); while (xmlr.geteventtype() == xmlstreamconstants.start_element) { jaxbelement<persontype> pt = unmarshaller.unmarshal(xmlr, persontype.class); if (xmlr.geteventtype() == xmlstreamconstants.characters) { xmlr.next(); } } memend = runtime.getruntime().freememory(); long end = system.currenttimemillis(); log.info("woodstox - (" + nbrrecords + "): total memory used: " + (memstart - memend)); log.info("woodstox - (" + nbrrecords + "): time taken in ms: " + (end - start)); } finally { xmlr.close(); } }
note the following line:
xmlinputfactory xmlif = xmlinputfactory2.newinstance();
where i pass in a stax2 xmlinputfactory. this uses the woodstox implementation.
the main loop
once the files are in place (you obtain this by passing -dcreate.xml=true), the main performs the following:
system.gc(); system.gc(); for (int i = 0; i < 10; i++) { main.readlargefilewithjaxb(new file(output_folder + file.separatorchar + "large-person-10000.xml"), 10000); main.readlargefilewithjaxb(new file(output_folder + file.separatorchar + "large-person-100000.xml"), 100000); main.readlargefilewithjaxb(new file(output_folder + file.separatorchar + "large-person-1000000.xml"), 1000000); main.readlargexmlwithstax(new file(output_folder + file.separatorchar + "large-person-10000.xml"), 10000); main.readlargexmlwithstax(new file(output_folder + file.separatorchar + "large-person-100000.xml"), 100000); main.readlargexmlwithstax(new file(output_folder + file.separatorchar + "large-person-1000000.xml"), 1000000); main.readlargexmlwithfasterstax(new file(output_folder + file.separatorchar + "large-person-10000.xml"), 10000); main.readlargexmlwithfasterstax(new file(output_folder + file.separatorchar + "large-person-100000.xml"), 100000); main.readlargexmlwithfasterstax(new file(output_folder + file.separatorchar + "large-person-1000000.xml"), 1000000); }
it invites the gc to run, although as we know this is at the gc thread discretion. it then executes each strategy 10 times, to normalise ram and cpu consumption. the final data are then collected by running an average on the ten runs.
the benchmark results for memory consumption
here follow some diagrams which show memory consumption across the different running environments, when unmarshalling 10,000 / 100,000 / 1,000,000 files.
you will probably notice that memory consumption for stax-related strategies often shows a negative value. this means that there was more free memory after unmarshalling all elements than there was at the beginning of the unmarshalling loop; this, in turn, suggests that the gc ran a lot more with stax than with jaxb. this is logical if one thinks about it; since with stax we don't keep all objects into memory there are more objects available for garbage collection. in this particular case i believe the persontype object created in the while loop gets eligible for gc and enters the young generation area and then it gets reclamed by the gc. this, however, should have a minimum impact on performance, since we know that claiming objects from the young generation space is done very efficiently.
summary for 10,000 xml elements
summary for 100,000 xml elements
summary for 1,000,000 xml elements
the benchmark results for processing speed
results for 10,000 elements
results for 100,000 elements
results for 1,000,000 elements
conclusions
the results on all three different environments, although with some differences, all tell us the same story:
- if you are looking for performance (e.g. xml unmarshalling speed), choose jaxb
-
if you are looking for low-memory usage (and are ready to sacrifice some performance speed), then use stax.
my personal opinion is also that i wouldn't go for woodstox, but i'd choose either jaxb (if i needed processing power and could afford the ram) or stax (if i didn't need top speed and was low on infrastructure resources). both these technologies are java standards and part of the jdk starting from java 6.
resources
benchmarker source code
- zip version: download large-xml-parser-1.0.0-snapshot-project
- tar.gz version: download large-xml-parser-1.0.0-snapshot-project.tar
- tar.bz2 version: download large-xml-parser-1.0.0-snapshot-project.tar
benchmarker executables:
- zip version: download large-xml-parser-1.0.0-snapshot-bin
- tar.gz version: download large-xml-parser-1.0.0-snapshot-bin.tar
- tar.bz2 version: download large-xml-parser-1.0.0-snapshot-bin.tar
data files:
- ubuntu 64-bit vm running environment: download stax-vs-jaxb-ubuntu-64-vm
- ubuntu 32-bit running environment : download stax-vs-jaxb-ubuntu-32-bit
- windows 7 ultimate running environment : download stax-vs-jaxb-windows7
from http://tedone.typepad.com/blog/2011/06/unmarshalling-benchmark-in-java-jaxb-vs-stax-vs-woodstox.html
Opinions expressed by DZone contributors are their own.
Comments