How to get amount of serialized bytes representing a Java object?

前端 未结 6 435
执笔经年
执笔经年 2021-02-01 20:45

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

6条回答
  •  花落未央
    2021-02-01 21:32

    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;
        }
    }
    

提交回复
热议问题