Re: Optimizing Java method
Lothar Kimmeringer wrote On 07/11/07 12:18,:
Benjamin White wrote:
The routine below is supposed to convert a String containing decimal
digits to a IBM mainframe Z/series packed decimal number. It seems to
consume a lot of CPU time. Background about this is at
http://benjaminjwhite.name/zdecimal/doc/index.html Is there a faster
way to code this?
To sum up things:
private static WeakHashMap cache = new WeakHashMap();
public static byte[] stringToPack(String str) throws DataException {
WeakReference wr = (WeakReference) cache.get(str);
if (wr != null && wr.get() != null){
return (byte[]) wr.get().clone();
}
One would need to measure to be sure, but the cache
strikes me as unlikely to help in this case. The lookup
will call str.hashCode(), and unless these String instances
have already been put in other maps it's likely that the
hashCode() method will actually compute the hash rather
than using a value already cached. The hash computation
is probably only a little faster than the conversion it
tries to avoid, so you'd need a *really* high hit rate
to make it worth while.
... but, as is usual with performance questions,
the gold standard is measurement.
byte[] res = new byte[16];
Insert `byte[15] = 0x0C;' here.
int shift = 4;
int currIndex = res.length; // decreased in loop
for (int i = str.length() - 1; i >= 0; i--){
char elem = str.charAt(i);
if (elem >= '0' && elem <= '9'){
if (shift != 0){
currIndex--;
}
Another micro-optimization, avoiding the branch:
currIndex -= shift >> 2;
res[currIndex] |= (byte) ((elem - '0') << shift);
shift ^= 4;
}
else{
switch(elem){
case ',':
case ' ':
case '.':
case '$':
case '+':{
break;
}
case '0':{
ITYM '-'.
res[res.length - 1] &= 0xf0;
res[res.length - 1] |= 0x0d;
Why use two operations to set one bit?
break;
}
default:{
throw new DataException("Invalid decimal digit: " + ch1 + " in string '" + str + "'");
}
}
}
}
cache.put(str, new WeakReference(res));
return res;
}
Not tested, just typed.
--
Eric.Sosman@sun.com