I'm curious, how far the optimization of the following code snippet will go.
To what I know, whenever the capacity of StringBuffer is extended, it costs some CPU work, because its content is required to be reallocated. However, I guess Java compiler optimization can precalculate the required capacity instead of doing multiple reallocations.
The question is: will the following snippet of code be optimized so?
public static String getGetRequestURL(String baseURL, Map<String, String> parameters) {
StringBuilder stringBuilder = new StringBuilder();
parameters.forEach(
(key, value) -> stringBuilder.append(key).append("=").append(value).append("&"));
return baseURL + "?" + stringBuilder.delete(stringBuilder.length(),1);
}
parameters, at runtime?StringBuilderis backed by achararray directly. If instead ofStringBuilder stringBuilder = new StringBuilder("");, you used something likeStringBuilder stringBuilder = new StringBuilder(256);you would find that the overhead is reduced, as theStringBuilderwill preallocate the internal buffer to256elements, reducing the possibility that the buffer needs to be resized dynamically (the size of the buffer and the size of the content are two different states which the builder will manage itself)Mapare defined at run time