2010-08-02 48 views
0

我需要使用JDOM来生成XML文件,这可能很大。我想知道多少额外的内存空间除了已经在内存中的数据(主要是字符串)之外,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 

正如你可以看到,使用了大约70MB的JDOM对象。

回答

1

JDOM需要这么多内存的原因是因为JDOM主要是像DOM这样的基于树的API(文档树是在内存中创建的,这是您使用它的方式)。但它比DOM更高效。如果要创建大型XML文档,你可能要考虑使用类似XMLStreamWriter捆绑与JDK6

这里有什么JDOM是不能够

article