What syntax would I use to get the number of bytes representing a string and compare them to the number of bytes representing an ArrayList
holding that string, for
I needed to check this accurately per-memcache write while investigating a server bug where memcache sizes were exceeded. To avoid the overhead of a big byte array for large objects I extended OutputStream as a counter:
public class CheckSerializedSize extends OutputStream {
/** Serialize obj and count the bytes */
public static long getSerializedSize(Serializable obj) {
try {
CheckSerializedSize counter = new CheckSerializedSize();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(counter);
objectOutputStream.writeObject(obj);
objectOutputStream.close();
return counter.getNBytes();
} catch (Exception e) {
// Serialization failed
return -1;
}
}
private long nBytes = 0;
private CheckSerializedSize() {}
@Override
public void write(int b) throws IOException {
++nBytes;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
nBytes += len;
}
public long getNBytes() {
return nBytes;
}
}