5

i have a question, what is the best way to append ints and Strings to build a new String? In the allocation debug tool i see too much allocations if i use the operator +.

But i have tried also with StringBuffer and there are still too much allocations.

Anyone can help me?

Thanks

bakkal
  • 54,350
  • 12
  • 131
  • 107
Gerardo
  • 5,800
  • 11
  • 66
  • 94
  • 1
    You might like this, lots of discussion on the details that might make something more or less efficient (bytecode dissection included!) http://stackoverflow.com/questions/2971315/string-stringbuffer-and-stringbuilder/ – bakkal Jun 05 '10 at 01:51

2 Answers2

13

Use StringBuilder or StringBuffer but with adequate initial capacity to avoid re-allocation. The default capacity is 16, so once you exceed that, the data has to be copied into a new bigger place. Use append not +.

int integer = 5;

StringBuilder s = new StringBuilder(100);
s.append("something");
s.append(integer);
s.append("more text");

Will allocate 100 slots upfront.

Reference: http://developer.android.com/reference/java/lang/StringBuilder.html

dvs
  • 12,324
  • 6
  • 38
  • 45
bakkal
  • 54,350
  • 12
  • 131
  • 107
0

You have specified you need to create a "new String", if you are creating any more objects than that, you should be able to optimise them away.

Note: it may be possible to remove all allocation, but only by passing the StringBuilder or something similar throughout the life of the string your have created. This may or may not be simple depending on how you use it.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130