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
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.
StringBuilder
只将文本附加到动态缓冲区,而MessageFormat
必须在附加数据之前解析给定的格式,然后StringBuilder
比MessageFormat
更有效。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.