2

I have a code which uses multiple SQL queries. Should i use String to store these different SQL queries or should i use a StringBuilder.

If using StringBuilder should i have each query in a new StringBuilder object or use a single StringBuilder object.

kiran
  • 21
  • 1

2 Answers2

3

String is Immutable and StringBuilder is Mutable i.e. no new object is created when you edit StringBuilder unlike String.

If your application is used in large scale then its advisable to use StringBuilder instead of String

NOTE:- String is Thread Safe while StringBuilder is not
Visky G
  • 91
  • 2
  • if i use a new StringBuilder object for each of these queries then will i not have as many objects as i would have had using String? – kiran Nov 16 '15 at 08:34
  • If your code is within one block/scope then use single object (Yes in this case your object count will be less obviously) but if you are going to share it through out the class then use different object. – Visky G Nov 16 '15 at 11:01
1

Well, if you are willing concatenate theses queries into one query part by part, then use unique StringBuilder object instead of concatenating String objects to each other. That's the best practise in terms of performance.

Avoid using unique StringBuilder for all (different) concatenation sets in your class, that thing must be dangerous if you're using threads. You have to define new StringBuilder object for each set of concatenated strings.

Hatem
  • 123
  • 11