我正在開發一個應用程序,它使用不同的組件創建一個XHTML文檔,我使用StringTemplate創建組件的文檔數據,然後將它們組合成一個大文檔。這是一個組件的例子:使用StringTemplate創建XML的性能?
public class BoxImpl extends AbstractContainerImpl implements Box {
private static final StringTemplate template;
static {
template = new StringTemplate(
"<div id=$id$>$content$</div>");
}
public BoxImpl(String id) {
this.setId(id);
}
@Override
public CharBuffer generate() {
// Get a local instance
StringTemplate template = BoxImpl.template.getInstanceOf();
// Set ID attribute of box
template.setAttribute("id", this.getId());
// Generate view for controls inside this container
CharBuffer inner = this.generateInner();
// Add inner data as content attribute
template.setAttribute("content", inner == null ? "" : inner.array());
// Return the result
return CharBuffer.wrap(BoxImpl.template.toString());
}
}
我的問題是,是不是更有效的實現使用XML DOM或者一個StringBuilder這種文檔構建的,相比StringTemplate的?
編輯:我不需要XML驗證。
我不確定這是否已在Java 6中更新,但在以前的版本中,我記得多個字符串連接會導致爲每次出現'+'運算符創建一個新的StringBuilder。 – MikeD 2010-07-08 21:15:38
它已從StringBuffer更改爲Java 1.5的StringBuilder。 – x4u 2010-07-08 21:25:56
@MikeD在1.4和之前,情況確實如此。我相信我記得觀察到5.0中的字節碼不再使用'+'運算符的'StringBuffer'。 – 2010-07-08 21:28:24