java序列化之比较

通过对Serializable和Externalizable的简单比较,哪怕是极其简单的类,发现序列化结果的大小相差很大,可以从80压到50,大家可以试一下,原因应该是前者是完全序列化,包含了class信息。

这就告诉我们,如果分布式环境下,传递java对象不要怕麻烦,自己实现一下Externalizable接口会快很多。

public class A implements Serializable{

	public int id = 1;
	public String name = "aaa";
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		
		A o = new A();
		FileOutputStream fos;
		try {
			fos = new FileOutputStream("/work/test/objects");
			
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(o);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		FileInputStream fis;
		
		try {
			fis = new FileInputStream("/work/test/objects");
			ObjectInputStream ois = new ObjectInputStream(fis);
			A oo = (A)ois.readObject();
			System.out.println(oo.id);
			System.out.println(oo.name);
//			System.out.println(ois.readInt());
//			System.out.println(ois.readObject());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

/**
 * 
 * same content, using external style will from 80 bytes to 50 bytes

 *
 */
public class B implements Externalizable{

	public int id = 1;
	public String name = "aaa";
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		
		B o = new B();
		FileOutputStream fos;
		try {
			fos = new FileOutputStream("f:/personal/test/objects2");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(o);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		FileInputStream fis;
		
		try {
			fis = new FileInputStream("/work/test/objects2");
			ObjectInputStream ois = new ObjectInputStream(fis);
			B oo = (B)ois.readObject();
			System.out.println(oo.id);
			System.out.println(oo.name);
//			System.out.println(ois.readInt());
//			System.out.println(ois.readObject());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeInt(id);
		out.writeObject(name);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		in.readInt();
		in.readObject();
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值