StAX と DOM が 2 つの同じドキュメントを作成するのに必要な時間を測定しようとしていました。XML の作成で DOM の方が速い理由がわかりません。私の StAX ライター用のコードはあまり良くないのかもしれません。ここにStAX(長いコード)があります
public static final int pocet =100000;
try {
String encoding = "UTF-8";
XMLOutputFactory f = XMLOutputFactory.newInstance();
XMLStreamWriter w = f.createXMLStreamWriter(
new FileOutputStream(subor),
encoding);
w.writeStartDocument(encoding, "1.0");
w.writeCharacters("\r\n");
w.writeStartElement("Noviny");
for (int i = 1; i <= pocet; i++) {
w.writeCharacters("\r\n ");
w.writeStartElement("Autor");
w.writeCharacters("\r\n ");
w.writeStartElement("Id");
String ID = Integer.toString(i);
w.writeCharacters(ID);
w.writeEndElement();
w.writeCharacters("\r\n ");
w.writeStartElement("Meno");
w.writeCharacters("Autor"+i);
w.writeEndElement();
w.writeCharacters("\r\n ");
w.writeStartElement("Email");
w.writeCharacters("Autor"+i+"@email.com");
w.writeEndElement();
w.writeCharacters("\r\n ");
w.writeStartElement("Tel_cislo");
w.writeAttribute("typ", "pevna");
w.writeCharacters("+4219");
w.writeEndElement();
w.writeCharacters("\r\n ");
w.writeStartElement("plat");
w.writeCharacters("5000");
w.writeEndElement();
w.writeCharacters("\r\n ");
w.writeEndElement();
w.writeCharacters("\r\n");
}
w.writeCharacters("\r\n");
w.writeEndElement();
w.writeCharacters("\r\n");
w.writeEndDocument();
w.close();
}
catch (Exception e) {
e.printStackTrace();
}
ドム
int pocet =1500000;
try {
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dfactory.newDocumentBuilder();
DOMImplementation domImpl = builder.getDOMImplementation();
Document document = domImpl.createDocument(null, "Noviny", null);
Node noviny = document.getDocumentElement();
for(int i = 0; i<pocet ; i++) {
Element autor = document.createElement("autor");
Element meno = document.createElement("meno");
Element id = document.createElement("id");
Element email = document.createElement("email");
Element tel = document.createElement("tel_cislo");
Element plat = document.createElement("plat");
Text textid = document.createTextNode(""+i);
Text textmeno = document.createTextNode("Autor"+i);
Text textemail = document.createTextNode("mail@gmail.com");
Text texttel = document.createTextNode("65456465465");
Text textplat = document.createTextNode("200");
noviny.appendChild(autor);
autor.appendChild(id);
id.appendChild(textid);
autor.appendChild(meno);
meno.appendChild(textmeno);
autor.appendChild(email);
email.appendChild(textemail);
autor.appendChild(tel);
tel.appendChild(texttel);
autor.appendChild(plat);
plat.appendChild(textplat);
}
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(document),new StreamResult(new File(subor)));
StAXの方がドキュメントを読むのが速いことは知っていますが、これを説明することはできません。StAXのコードがかなり悪いことを除いて
ありがとう