【发布时间】:2015-06-10 03:52:01
【问题描述】:
我尝试序列化 Byte 和 Integer 的实例,当它们在另一端收到时它们占用了多少空间,这让我感到震惊。为什么做一个 Integer 只需要 4 个字节,但序列化时却占用了 10 倍以上的字节数?我的意思是在 C++ 中,最终类有一个 64 位的类标识符,以及它的内容。脱离这个逻辑,我希望整数在序列化时占用 64 + 32 或 96 位。
import java.io.*;
public class Test {
public static void main (String[] ar) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(new Integer(32));
byte[] yourBytes = bos.toByteArray();
System.out.println("length: " + yourBytes.length + " bytes");
}
}
输出:
长度:81 字节
更新:
public static void main(String[] args) throws IOException {
{
ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
ObjectOutput out1 = new ObjectOutputStream(bos1);
out1.writeObject(new Boolean(false));
byte[] yourBytes = bos1.toByteArray();
System.out.println("1 Boolean length: " + yourBytes.length);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
for (int i = 0; i < 1000; ++i) {
out.writeObject(new Boolean(true)); // 47 bytes
}
byte[] yourBytes = bos.toByteArray();
System.out.println("1000 Booleans length: " + yourBytes.length); // 7040 bytes
final int count = 1000;
ArrayList<Boolean> listBoolean = new ArrayList<>(count);
listBoolean.addAll(Collections.nCopies(count, Boolean.TRUE));
System.out.printf("ArrayList: %d%n", sizeOf(listBoolean)); // 5096 bytes
Boolean[] arrayBoolean = new Boolean[count];
Arrays.fill(arrayBoolean, true);
System.out.printf("Boolean[]: %d%n", sizeOf(arrayBoolean)); // 5083 bytes
boolean[] array = new boolean[count];
Arrays.fill(array, true);
System.out.printf("boolean[]: %d%n", sizeOf(array)); // 1027 bytes
BitSet bits = new BitSet(count);
bits.set(0, count);
System.out.printf("BitSet: %d%n", sizeOf(bits)); // 201 bytes
}
static int sizeOf(Serializable obj) throws IOException {
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ObjectOutputStream objsOut = new ObjectOutputStream(bytesOut);
objsOut.writeObject(obj);
return bytesOut.toByteArray().length;
}
输出:
1 个布尔值长度:47(每个布尔值 47 个字节)
1000 个布尔值长度:7040(每个布尔值 7 个字节)
ArrayList:5096(每个布尔值 5 个字节)
Boolean[]: 5083(每个布尔值 5 个字节)
boolean[]: 1027(每个布尔值 1 个字节)
BitSet:201(每个布尔值 1 字节的 1/5)
【问题讨论】:
-
Java 序列化有一个非常特殊的目的。它不等同于 JSON 或 Protocol Buffers,对于只需要类似内容的用例来说,它可能有点过分了。
标签: java serialization