Performance issue: “java.text.MessageFormat.format” vs “StringBuilder”

▼魔方 西西 提交于 2019-12-21 11:30:12

问题


I want to know in compare of MessageFormat or StringBuilder class. Let say an example i have a String. For performance wise which one is fast among: java.text.MessageFormat.format or StringBuilder("Test ").append("Hello ")?

String txt = java.text.MessageFormat.format("Test {0}"," Hello") 
String txt1=   new StringBuilder("Test ").append("Hello ")

I just want to know which one is use in case of best practice or performance wise


回答1:


Try it yourself:

long start = System.nanoTime();
String txt = MessageFormat.format("Test {0}"," Hello");
System.out.println("MessageFormat: " + (System.nanoTime() - start) + " ns");

start = System.nanoTime();
String txt1 = new StringBuilder("Test ").append("Hello").toString();
System.out.println("StringBuilder: " + (System.nanoTime() - start) + " ns");

Output:

MessageFormat: 1125974 ns

StringBuilder: 16705 ns

Conclusion:

StringBuilder works much faster because it just adds some chars to existing array.




回答2:


StringBuilder does only append text to a dynamic buffer, while MessageFormat has to parse the given format before appending the data, then StringBuilder is more efficient than MessageFormat.



来源:https://stackoverflow.com/questions/15358090/performance-issue-java-text-messageformat-format-vs-stringbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!