private static final Group[] toGroups (String string)
{
int partialGroupSize = string.length() % GROUP_SIZE;
boolean hasPartialGroup = partialGroupSize != 0;
int nGroupOffset = hasPartialGroup ? 1 : 0;
int nGroup = string.length() / GROUP_SIZE + nGroupOffset;
Group[] groups = new Group[nGroup];
for (int i = 0; i < nGroup; i++) {
boolean isFirstGroup = i == 0;
int beginIndex = isFirstGroup ? i :
GROUP_SIZE * (i - nGroupOffset) + partialGroupSize;
int endIndex = isFirstGroup && hasPartialGroup ?
beginIndex + partialGroupSize :
beginIndex + GROUP_SIZE;
groups[i] = new Group(Integer.parseInt(string.substring(beginIndex,
endIndex)));
}
return groups;
}
My first question is one that I found different discussions about, but I still don’t know what I should do.
The method toGroups is only called once in the program, therefore .length() is only called twice on string of toGroups in the program. So with regards to performance and readability, should I replace string.length() with length where int length = string.length();?
Id est:
int length = string.length();
int partialGroupSize = length % GROUP_SIZE;
boolean hasPartialGroup = partialGroupSize != 0;
int nGroupOffset = hasPartialGroup ? 1 : 0;
int nGroup = length / GROUP_SIZE + nGroupOffset;
My second question is: within the for loop, given that when the predicate of the beginIndex conditional assignment, isFirstGroup, is true, i must be 0; should I replace the consequent of the beginIndex conditional with a literal 0?
Id est:
int beginIndex = isFirstGroup ? 0 :
GROUP_SIZE * (i - nGroupOffset) + partialGroupSize;
I reason that because the consequent of beginIndex is always 0, using the equivalent i iterator creates an ambiguity in the constancy/variableness of the consequent.
Readability is a more important attribute of a well written program than performance. Indeed, readability is second only to correctness (IMO).
Performance is generally speaking a minor issue. And in the cases where it is important, large-scale algorithmic efficiency is more critical than “micro” issues such as whether you call a fast method such as
String.length()once or twice.(Indeed, there is a good chance that the JIT compiler can figure out that it can safely “hoist” the
String.length()call out of the loop. And even if it can’t, the next generation of JIT compiler may be able to do this optimization.)In general, it is best to leave micro-optimizations like this to the JIT compiler, and focus your effort on more important things. Only micro-optimize if you have clear evidence (e.g. from profiling) of a significant bottleneck in your code.
Yes.
Don’t line all your declaration / assignment statements up like that: