Thursday, July 23, 2009

Homemade recipe

This is another example of how simple "homemade" approach significantly outperforms patented generic methods. How often you needed to convert byte array into String object and vice versa? The recommended methods always require the name of Charset. Since in my case the charset is always UTF-8, I hardcoded it.
When converting from byte array to String, something like following can be used:
final static String b2s_recommended(byte[] bb) {
    try {
        return new String(bb, 0, bb.length, "UTF-8");
    } catch(Exception ex) {
        throw new RuntimeException(ex.getMessage());
    }
}
   
   

When converting from String to byte array something like following can be used:
final static byte[] s2b_recommended(String s) {
    try {
        return s.getBytes("UTF-8");
    } catch(Exception ex) {
        throw new RuntimeException(ex.getMessage());
    }
}
   
   

Corresponding "homemade" methods that don't pretend to be generic, can look like following:
final static String b2s_homemade(byte[] bb) {
    char[] cc = new char[bb.length];
    for (int i = 0; i < bb.length; ++i) {
        cc[i] = (char) bb[i];
    }
    return new String(cc);
}
   
final static byte[] s2b_homemade(String s) {
    byte[] bb = new byte[s.length()];
    for (int i = 0; i < bb.length; ++i) {
        bb[i] = (byte) s.charAt(i);
    }
    return bb;
}
   

On my computer homemade b2s outperformed recommended one with factor of 4.2 . For the s2b the performance bust was 6.0 !

No comments:

Post a Comment