我正在测试 DOM、SAX 和 StAX 的效率。
基本上我所做的是使用 Spring 秒表和不同大小的 XML,然后比较结果。
我还认为我可以测量元素加载到对象和对象到数组的时间,但这与解析无关。
这是我的代码 用于 SAX
StopWatch stopWatch = new StopWatch("SAX");
stopWatch.start("SAX");
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(false);
SAXParser sp = spf.newSAXParser();
XMLReader parser = sp.getXMLReader();
parser.setErrorHandler(new Chyby());
parser.setContentHandler(new DefaultHandler());
parser.parse(file);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
对于 StAX
int temp = 0;
StopWatch stopWatch = new StopWatch("StAX");
stopWatch.start("StAX");
XMLInputFactory f = XMLInputFactory.newInstance();
XMLStreamReader r = f.createXMLStreamReader( new FileInputStream( file ));
while (r.hasNext()==true){
temp++;
r.next();
}
System.out.println("parsed");
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
DOM
StopWatch stopWatch = new StopWatch("DOM");
stopWatch.start("DOM");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(subor);
System.out.println("parsed");
System.out.println("----------------\n");
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
我的问题是:我做得对吗?还有其他测试解析器的方法吗? 谢谢
最佳答案
创建 JAXP 工厂类是一项非常昂贵的操作,其成本在很大程度上取决于类路径中存在的 JAR。你真的不想衡量它。
您需要注意消除 Java 启动成本。在开始测量之前解析一些文档。重复运行测量,对结果进行平均,并检查结果是否一致。
我会用不同大小的文档运行测试。通常,成本为 (ax+b),其中 x 是文档大小。此处的数字 'b' 表示“每个文档的开销”,如果文档很小,它可能会非常重要。
在 DOM 的情况下,很可能会发生垃圾回收,这会扭曲结果,因为它们发生在不可预测的时间。有时建议在已知时间强制进行垃圾收集以获得一致的测量值。
关于Java 解析器测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16328594/