2

I know code snippet-1 is poor coding quality, best practice is code snippet-2.
But does it decrease performance in code snippet-1 ?
Is there any performance between these two snippets ? If yes, then how ?

Snippet-1

StringBuffer strBuffer = new StringBuffer();
strBuffer.append("Text line 1");
strBuffer.append("Text line 2");
strBuffer.append("Text line 3");
strBuffer.append("Text line 4");
strBuffer.append("Text line 5");

Snippet-2

StringBuffer strBuffer = new StringBuffer();
strBuffer.append("Text line 1")
        .append("Text line 2")
        .append("Text line 3")
        .append("Text line 4")
        .append("Text line 5");

3 Answers 3

2

First, for performance you should use StringBuilder (not StringBuffer). StringBuilder is more efficient because (unlike StringBuffer) not every method is synchronized. Finally, your posted examples will almost certainly have the same performance so use the style you prefer.

Sign up to request clarification or add additional context in comments.

2 Comments

My application is thread safe, so there would be not issue if I use StringBuffer instead of StringBuilder, right ?
@unknown StringBuilder is faster and I would prefer it to StringBuffer in your case.
1

HI I have written one small java program to check this (both ways) because there is not any other explanation. I have tried with two different OS also and I think somehow Snippet-2 is every time winner in performance. I have even put both in the for loop which runs for more than 1000 times and every time I have seen Snippet-2 was getting less time than 1.

You can also try it your self with all possible ways.

Its fun :)

Comments

0

Code presentation is often a matter of "taste", but these two structures should have equivalent optimization within the Java Compiler that you use! (Compilers are tasked with taking what you write and making it efficient, in the case of Java such optimization may occur both when the language is compiled into bytecode and with the bytecode is handled at execution time (or in the case of Android applications, when the "APK" itself is "compiled" when it is changed/updated).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.