JDOM需要多少“开销”内存来生成XML文件?

时间:2010-08-02 03:38:14

标签: java memory jdom

我需要使用JDOM来生成XML文件,这可能非常大。我想知道除了已经在内存中的数据(主要是字符串)之外,还需要多少额外的内存空间 JDOM。我编写了一个简单的程序进行测试,结果发现开销大约是XML内容的两倍。

有没有人知道为什么JDOM需要那么多额外的内存?如果有办法我可以优化它? JDOM对象不应该只保留对现有字符串的引用吗?

以下是我用来测试的程序:

public class TestJdomMemoryOverhead {
    private static Runtime runtime = Runtime.getRuntime();

    public static void gc() {
        // Try to give the JVM some hints to run garbage collection
        for (int i = 0; i < 5; i++) {
            runtime.runFinalization();
            runtime.gc();
            Thread.currentThread().yield();
        }
    }

    public static void generateXml(List<String> filenames) throws IOException {
        // generate a simple XML file by these file names. It looks like:
        // <?xml version="1.0" encoding="UTF-8"?>
        // <files>
        // <f n="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" />
        // <f n="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" />
        // <f n="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" />
        // ....
        // ....
        // </files>
        Element filesElem = new Element("files");
        Document doc = new Document(filesElem);
        for (String name : filenames) {
            Element fileElem = new Element("f");
            fileElem.setAttribute("n", name);
            filesElem.addContent(fileElem);
        }
        gc();
        System.out.println("After generating JDOM objects: " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes");
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        BufferedWriter writer = new BufferedWriter(new FileWriter("test.xml", false));
        outputter.output(doc, writer);
        writer.close();
        gc();
        System.out.println("After writing to XML file: " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes");
    }

    public static void main(String[] cmdArgs) throws IOException {
        List<String> filenames = new ArrayList<String>();
        StringBuilder builder = new StringBuilder();
        // 30 unicode chracters, repated 500,000 times. The memory to store
        // these file name strings should be about 30MB.
        builder.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        for (int i = 0; i < 500000; i++) {
            filenames.add(builder.toString());
        }
        gc();
        System.out.println("After generating file names: " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes");
        generateXml(filenames);
        gc();
        System.out.println("Get back to main: " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes");
    }
}

输出结果为:

After generating file names: 51941096 bytes
After generating JDOM objects: 125766824 bytes
After writing to XML file: 126036768 bytes
Get back to main: 51087440 bytes

如您所见,JDOM对象使用了大约70MB。

1 个答案:

答案 0 :(得分:1)

JDOM需要如此多内存的原因是因为JDOM主要是基于树的API,如DOM(文档树是在内存中创建的,就像你使用它一样)。但它比DOM更具性能。如果要创建大型XML文档,可能需要考虑使用与jdk6捆绑在一起的XMLStreamWriter

这是关于JDOM无法实现的短article