1

Currently, when javac encounters a String concatenation, it converts the code to use a StringBuilder. For example:

String a = String.valueOf(System.currentTimeMillis());
    String b = String.valueOf(System.currentTimeMillis());
    String c = String.valueOf(System.currentTimeMillis());
    String d = a + b + c + "_IND";

becomes something like

String d = new StringBuilder().append(a).append(b).append(c).append("_IND");

Since the StringBuilder is not explicitly sized, the default size is used and often results in expandCapacity calls at runtime when the default size is too small.

While profiling the application we saw many such operations e.g. build keys for various HashMaps, build unique key for each element in JSF etc which results in extra memory usage.

Is there any better way to reduce this.

T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • Since you're only appending currentTimeMillis, you have an initial idea of the StringBuilder size no? Something _like_ new StringBuilder(System.currentTimeMillis().toString().length * 3 + 4) – Pieter De Bie Mar 08 '17 at 07:09
  • No that is just an example, you can use any thing for concatination each time they uses string builder – T-Bag Mar 08 '17 at 07:10
  • Possible duplicate of [Most efficient initial capacity size for StringBuilder?](http://stackoverflow.com/questions/13360229/most-efficient-initial-capacity-size-for-stringbuilder) – Jeremy Mar 08 '17 at 07:14
  • Well, isn't the work-around obvious? Use a StringBuilder, and give it an appropriate size. If you are saying that you donot know the size, then there is no magic to prevent automatic resizing. Note: it does not result in extra memory use -- it does however create more garbage. You don't provide much info about your use case, but if this is causing problems you may want to look at redesigning this part of your application to not rely on strings so much. – john16384 Mar 08 '17 at 08:38

1 Answers1

2

In cases where you are trying to insert bigger strings in the StringBuilder it is always wiseable to interpret the size of the big string and initialize your StringBuider with the somewhat more than estimated size as its default capacity.

Derive an emphirical formulae to come up with the intializing capacity for StringBuilder so that you control the cost of under- and over-estimating the sizes.

Because StringBuilder stores the string that is being built in a form of char array. The capacity of StringBuilder is the length of this array. Once the array would overflow, a new (longer) array is allocated and contents are transferred to it. This makes the capacity rise.

mhasan
  • 3,703
  • 1
  • 18
  • 37