Re: how can i optimize the given below code
Lew wrote:
public class FilledStringGenerator {
private String source;
public String generate(int length) {
if (length < 0)
throw new IllegalArgumentException();
String source = this.source;
Why are you hiding the instance member?
Well, it is not necessary. It just happened during adding simple
concurrency support to my initial implementation (without changing it).
Initially the method was operating on the instance variable only.
while (source.length() < length)
this.source = source += source;
Why are you assigning the string twice each iteration, once to the local
variable and once to the instance variable?
It's to let access as soon as possible the newly created string by the
other concurrently running threads.
Yes, I know, that the Java memory model do not guarantee this (field
should be volatile to ensure this). But it gives the other threads at
least a chance to reference a new instance variable still without adding
the synchronization overheads.
Note that the assignment to the local is important for the logic, which
is correct independently of the memory model, i.e. the method will
always return the correct result.
return source.substring(0, length);
}
}
This, of courrse, completely kills the OP's stated intention of
/optimizing/ the algorithm.
Hmmm. Do you think that filling an array char by char and then creating
a string is more optimal than just creating a substring of the already
filled string?
piotr