Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Clearing StringBuffer contents

All,

I was wondering if clearing a StringBuffer contents using the setLength(0) would make sense. i.e. Is it better to do :

while (<some condition>)
{
    stringBufferVariable = new StringBuffer(128);
    stringBufferVariable.append(<something>)
                        .append(<more>)
                        ... ;
    Append stringBufferVariable.toString() to a file;
    stringBufferVariable.setLength(0);
}

My questions:
1 > Will this still have better performance than having a String object to append the contents?

I am not really sure how reinitializing the StringBuffer variable would affect the performance and hence the question.

Please pour in your comments

[edit]: Removed the 2nd question about comparing to StringBuilder since I have understood there nothing more to look into based on responses.

like image 776
name_masked Avatar asked Dec 29 '22 05:12

name_masked


1 Answers

Better than concatenating strings?

If you're asking whether

stringBufferVariable.append("something")
                    .append("more");
...

will perform better than concatenating with +, then yes, usually. That's the whole reason these classes exist. Object creation is expensive compared to updating the values in a char array.

It appears most if not all compilers now convert string concatenation into using StringBuilder in simple cases such as str = "something" + "more" + "...";. The only performance difference I can then see is that the compiler won't have the advantage of setting the initial size. Benchmarks would tell you whether the difference is enough to matter. Using + would make for more readable code though.

From what I've read, the compiler apparently can't optimize concatenation done in a loop when it's something like

String str = "";
for (int i = 0; i < 10000; i++) {
    str = str + i + ",";
}

so in those cases you would still want to explicitly use StringBuilder.

StringBuilder vs StringBuffer

StringBuilder is not thread-safe while StringBuffer is, but they are otherwise the same. The synchronization performed in StringBuffer makes it slower, so StringBuilder is faster and should be used unless you need the synchronization.

Should you use setLength?

The way your example is currently written I don't think the call to setLength gets you anything, since you're creating a new StringBuffer on each pass through the loop. What you should really do is

StringBuilder sb = new StringBuilder(128);
while (<some condition>) {
    sb.append(<something>)
      .append(<more>)
      ... ;
    // Append stringBufferVariable.toString() to a file;
    sb.setLength(0);
}

This avoids unnecessary object creation and setLength will only be updating an internal int variable in this case.

like image 113
Brad Mace Avatar answered Dec 30 '22 20:12

Brad Mace