0

I have below code in my application at many places. I am using it to prepare SQL queries.

Approach 1:

private String sampleMethod(String name) {
    //null check
    StringBuilder sb = new StringBuilder("Welcome ");
    sb.append(name);
    sb.append(", Have a good day!");
    //System.out.println(sb.toString());
    return sb.toString();
}

Approach 2:

private String sampleMethod(String name) {
    //null check
    //System.out.println("Welcome " + name + ", Have a good day!");
    return "Welcome " + name + ", Have a good day!";
}
  1. Which approach should I use?
  2. Does both have same memory usage?

Thank you.

Naman Gala
  • 4,670
  • 1
  • 21
  • 55
  • 2
    AFAIK - The second approach will be converted to the first by the compiler automatically. One of the use cases for using `StringBuilder` would be if you were doing `String` concatenation within a loop – MadProgrammer Mar 27 '15 at 05:32
  • @MadProgrammer, Thanks. Understood your point. – Naman Gala Mar 27 '15 at 05:34
  • 1
    Please refere :http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java – Prabhaker A Mar 27 '15 at 05:35
  • 1
    @Prabhaker, Thanks for the link. It explains much about it. `Anyone referring this question in future, should check out above link`. – Naman Gala Mar 27 '15 at 05:41

3 Answers3

1

Internally both approaches are nearly the same. Use whatever makes your code easier to read and maintain. Worry over memory consumption and performance only when you have problems in that regard. That will be much less than you think.

Thomas Stets
  • 3,015
  • 4
  • 17
  • 29
  • As I am not much aware of how compiler works, thanks for pointing out that internally both approaches are the same. – Naman Gala Mar 27 '15 at 05:40
1

In modern versions of Java compilers, the idiom:

String x = a + b + c;

is internally transformed into:

String x = new StringBuilder().append(a).append(b).append(c).toString();

so, unless you're working with a really old compiler, both would be practically the same.

That doesn't mean that StringBuilder is not useful any more, it can still be used in for and while loops.

morgano
  • 17,210
  • 10
  • 45
  • 56
0

Stringbuilder does not re create object, in that case, the memory usages is better. But String do re create object. Other than that, both's functionality are same.

Saqib Rezwan
  • 1,382
  • 14
  • 20