Gordon
Gordon

Reputation: 1914

Implicit StringBuilder size

I almost always use StringBuilder(int) to avoid silly reallocations with the tiny default capacity. Does any javac implementation do anything special to use an appropriate capacity for implicit uses of StringBuilder in concatenation? Would "abcdefghijklmnopqrstuvwxyz" + numbers + "!.?:" use at least an initial capacity of 30 given the literal lengths?

Upvotes: 2

Views: 211

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198163

Yes, it is going to be that smart -- smarter, actually -- in Java 9. (This is something I can loosely claim I was a part of -- I made the original suggestion to presize StringBuilders, and that inspired the better, more powerful approach they ended up with.)

http://openjdk.java.net/jeps/280 specifically mentions, among other issues, that "sometimes we need to presize the StringBuilder appropriately," and that's a specific improvement being made.

(And the moral of the story is, write your code as simply and readably as possible and let the compiler and JIT take care of the optimizations that are properly their job.)

Upvotes: 4

CAW
CAW

Reputation: 389

This may depend on your compiler version, settings etc.

To test this, I created a simple method:

public static void main(String[] args) {
    System.out.println("abcdefghijklmnopqrstuvwxyz" + args[0] + "!.?:");
}

And after compiling and then running it through a decompiler, we get the following result:

System.out.println((new StringBuilder()).append("abcdefghijklmnopqrstuvwxyz").append(args[0]).append("!.?:").toString());

So it would seem that, at least with some javac versions, it just uses the default.

Manually inspecting the bytecode indicates the same thing.

Upvotes: -1

Related Questions