Initializing StringBuilder in Java

I needed to use this method , and, looking at the source code, I noticed the StringBuilder initialization, which is not familiar to me (I always use the constructor without arguments from StringBuilder , i.e. new StringBuilder() ).

In the method:

 StringBuilder sb = new StringBuilder(items.size() << 3); 

From JavaDoc:

java.lang.StringBuilder.StringBuilder (int capacity)

Creates a string builder with no characters in it, and the initial capacity specified by the capacity argument.

Why is a bit shift needed here?

Source:

 /** Creates a backslash escaped string, joining all the items. */ public static String join(List<?> items, char separator) { StringBuilder sb = new StringBuilder(items.size() << 3); boolean first=true; for (Object o : items) { String item = o.toString(); if (first) { first = false; } else { sb.append(separator); } for (int i=0; i<item.length(); i++) { char ch = item.charAt(i); if (ch=='\\' || ch == separator) { sb.append('\\'); } sb.append(ch); } } return sb.toString(); } 
+6
source share
3 answers

Bitshift by 3 means multiplying by 2 ^ 3, which is 8. The author must assume that each element will take no more than 8 characters in the resulting string. Therefore, he or she initialized StringBuilder with the ability to make it work efficiently. If the assumption is correct, StringBuilder does not redistribute the internal structures.

+3
source

X <3 means multiplying X by 8. In your situation, this means allocating space for 8 * list.size () characters. In general, you do not have to worry about the details of the implementation of the class you are using.

+2
source

It is the ability to multiply by 8 items.size() .
I think that the encoder would simply assume initialCapacity to prevent (or minimize to a minimum) StringBuilder() redistribution of internal buffers.

0
source

Source: https://habr.com/ru/post/951208/


All Articles