GWT 字符串连接运算符 +与字符串缓冲区
我必须为 GWT 应用程序选择一种高效的字符串串联方式。为此,我做了一个小测试,认为这对其他人了解结果也会有帮助。
因此,令人惊讶的是差异非常小:1000000 个串联约为 100 毫秒。所以,请从代码阅读的角度选择合适的。
我的测试很简单:
// + operator
private void str() {
Date start = new Date();
String out = "";
for(int a=0;a<1000000;a++) {
out += "item" + a;
}
Date end = new Date();
MessageBar.error("str:" + (end.getTime() - start.getTime()));
}
// StringBuffer implementation
private void sb() {
Date start = new Date();
StringBuffer out = new StringBuffer();
for(int a=0;a<1000000;a++) {
out.append("item" + a);
}
Date end = new Date();
MessageBar.error("sb:" + (end.getTime() - start.getTime()));
}
结果是:
str:1612
str:1788
str:1579
sb:1765
sb:1818
sb:1839
I had to choose a way of efficient string string concatenation for GWT application. For this I did a small test and thought it will be helpful for others to know results as well.
So, surprisingly difference is quite minor: ~100ms for 1000000 concatenations. So, please choose appropriate from code reading point of view.
My testing was simple:
// + operator
private void str() {
Date start = new Date();
String out = "";
for(int a=0;a<1000000;a++) {
out += "item" + a;
}
Date end = new Date();
MessageBar.error("str:" + (end.getTime() - start.getTime()));
}
// StringBuffer implementation
private void sb() {
Date start = new Date();
StringBuffer out = new StringBuffer();
for(int a=0;a<1000000;a++) {
out.append("item" + a);
}
Date end = new Date();
MessageBar.error("sb:" + (end.getTime() - start.getTime()));
}
Results were:
str:1612
str:1788
str:1579
sb:1765
sb:1818
sb:1839
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是 stan229 的问题和蜥蜴比尔的请求。
不同浏览器的性能差异确实很有趣。对我来说,问题是“选择哪种串联方法”,我得到了我想要的答案。但这里有更多测试结果:
所以,我得到的答案是:+ 运算符提供更好的性能
我的下一个问题是什么提供更好的性能:
一旦我进行测试,或者如果您有答案 - 请发帖
Following question of stan229 and request of Bill the Lizard.
That's indeed interesting how performance differs from browser to browser. For me the question was "which concatenation method to choose" and I got the answer I wanted. But here is more test results:
So, the answer I got is: + operator gives better performance
My next question is what gives better performance:
will post this once I do the test or, if you have the answer - please post
您可以查看 gwt 源代码并了解 StringBuffer/StringBuilder 是如何模拟的。
GWT 为浏览器选择性能最佳的字符串连接方式。
GWT 2.2.0 StringBuffer 源
You can look at the gwt source code and see how StringBuffer/StringBuilder are emulated.
GWT chooses the best perfomant way for string concatenation for the browsers.
GWT 2.2.0 StringBuffer source