Frank Jacobsen wrote:I use a string buffer, because it is faster to append than to create a new string each time.
As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
Frank Jacobsen wrote:
Faster = The fastest way this can be done.
Campbell Ritchie wrote:I think that method is unreliable because it returns a mutable and thread‑unsafe reference type, viz. a StringBuilder. You don't know what users will do with that StringBuilder object. I suggest you call toString() on it and return a String reference.
You have an inefficiency in that you are using the + operator on a String; it would be better to declare the String and compose it with +s in the same expression; what's more that will make the String object into a compile‑time constant and all the String composition will be done by the javac tool. It will also make line 4 short enough to read.
Don't use milliseconds; use System.nanoTime() instead.
Run your exercise twice and only time the second run; that will allow the runtime to make any optimisations before you start timing. For example, line 4 might be optimised to run only once.
It is only a tiny delay but since OP didn't make anything final, (as you pointed out) the + operator in line 5 has to run at runtime rather than compile time.
Tim Holloway wrote:. . . The problem with "allowedStrings" isn't the use of the concatenation operator. . . . constant-folding optimisation can be done at compile time.
As I showed; my concatenated Strings are compile‑time constants.
However, we do have ways to split long strings . . .
I missed a bit out; that should read
Yesterday, I wrote:
Campbell Ritchie wrote:... since OP didn't make anything final, (as you pointed out) the + operator in line 5 has to run at runtime rather than compile time.