开发者

GWT string concatenation operator + vs. stringbuffer

开发者 https://www.devze.com 2023-02-27 11:48 出处:网络
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.

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
pr开发者_如何学运维ivate 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


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:

chrome 10.0.648.204:
str: 748
sb : 849

firefox 3.6.16:
str: 1681
sb : 1861

ie 8:
str: 2484
sb : 4094

opera 11.10
str: 802
sb : 792

So, the answer I got is: + operator gives better performance

My next question is what gives better performance:

int i=0;
// this
String result = String.valueOf(i);
// or this
String result = i + "";

will post this once I do the test or, if you have the answer - please post


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

A fast way to create strings using multiple appends. This is implemented using a StringBufferImpl that is chosen with deferred binding. Most methods will give expected performance results...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号