I wrote an n-ary ADT tree that works fine. However, I need to save the serialization in a variable of the calling class. eg.
DomTree<String> a = Data.createTreeInstance("very_large_file.xml"); String x = a.toString();
I wrote a method that serves the purpose of exactly how I need it, but on the very large inputs that it takes forever (20 minutes per 100 MB xml file). I timed the methods and built the tree from the XML file quickly, but the call toString (), as shown above, is very slow.
@Override public String toString(){ return printTree(this); } public String printTree(AbstractTree<E> tree){ if (tree.isLeaf()){ return tree.getNodeName(); }else{ String tStr = tree.getNodeName() + "("; int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ tStr += printTree(child.next()) + ", "; i++; } tStr += printTree(child.next()) + ")"; return tStr; } }
I assume this is due to the way the lines are built, and not how the tree goes? Is there a better way to do this?
UPDATE. Following the Skaffman example, the following code gives outOfMemoryError for very large input.
@Override public String toString(){ StringBuilder buffer = new StringBuilder(); printTree(this, buffer); return buffer.toString();
}
public String printTree(AbstractTree<E> tree, StringBuilder buffer){ if (tree.isLeaf()){ return tree.getNodeName(); }else{ buffer.append(tree.getNodeName()); buffer.append("("); int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ buffer.append(printTree(child.next(), buffer)); buffer.append(", "); i++; } buffer.append(printTree(child.next(), buffer)); buffer.append(")"); return buffer.toString(); } }
UPDATE: now works fine using the Skaffmans example
java optimization string-concatenation
Robert
source share