Nathaniel D. Waggoner
Nathaniel D. Waggoner

Reputation: 2886

Is String Builder or ""+someNumb more efficient/correct for small cases?

II've been in the habit of doing:

int num = 12;
String text = ""+12;

for a long time, but I've found that to be a very inefficient mechanism for the large number of additions.

For those cases I generally do something like:

// this is psuedo code here..
FileInputStream fis = new FileInputStream(fis);
StringBuilder builder = new StringBuilder();
while(input.hasNext()) {
   builder.append(input.nextString());
}

My question is: When coding for Android (vs the General Java case) Is the performance trade off at the small case worth using String Builder, or are there any other reasons to prefer String Builder in these small cases? It seems like it's a lot of extra typing int he simple case presented above. I also suspect (though I have not confirmed) that the memory allocations in the simple case are probably not worth it.

Edit: Suppose that the values being appended aren't known at compile time, I.E. they aren't constants.

Also the example above of ""+12 is a poorly chosen example.. Suppose it was

String userGeneratedText  = textInput.getText().toString();
int someVal = intInput.getInt();

String finalVal = userGeneratedText+someVal;

Upvotes: 1

Views: 93

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

If your code is short as you shown here:

String text = "foo" + 12;

The compiler will automatically replace the concatenation to use StringBuilder:

String text = new StringBuilder().append("foo").append(12).toString();

So don't worry about the inefficiency of this code, because it will work better than you expect.

For cases when you need to append very large Strings or you don't know how many objects (Strings, ints, booleans, etc) will you concatenate, use a StringBuilder as you do in your second code sample.

Here's a more in depth explanation about how the String concatenation works: http://blog.eyallupu.com/2010/09/under-hood-of-java-strings.html

Upvotes: 4

Faizan Mubasher
Faizan Mubasher

Reputation: 4569

As far as I know! string is immutable object. It means that its state cannot be changed, when ever you append value to string type then what happened is compiler deletes old one create new one with apended value.

But this is not the case with StringBuilder. StringBuilder is mutable which means its old value won't be destroyed. Any change/append will be taken place with existing object.

I know I am not covering in depth but this might cause major performance difference.

Upvotes: -1

Related Questions