在通常的java程序中,常常會把對象進行序列化,但通常咱們都是基於JDK自帶的java序列化,那麼這種序列化的性能到底如何,在咱們的網絡編程中可否採用這種序列化,來將咱們的消息進行傳遞呢!話很少少,直接貼出代碼。java
import java.io.Serializable; import java.nio.ByteBuffer; /** * @FileName Person.java * @Description: 編碼測試類 * * @Date 2016年3月4日 * @author Administroter * @version 1.0 * */ public class Person implements Serializable{ //默認的序列號ID private static final long serialVersionUID = 1L; private int userId; private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Person buildUserID(int userId){ this.userId = userId; return this; } public Person buildUserName(String userName){ this.userName = userName; return this; } /** * @Title: codeC * @Description:採用通用的ByteBuffer的通用二進制編碼技術將Person對象轉成byte數組,用於和 * java序列化後的碼流進行對比 * @return * @author Administroter * @date 2016年3月4日 */ public byte[] codeC(){ //建立一個容量爲1024的字節緩衝區 ByteBuffer buffer = ByteBuffer.allocate(1024); //將userName編碼爲byte序列,並將結果存儲到value byte數組中 byte[] value = this.userName.getBytes(); buffer.putInt(value.length); buffer.put(value); buffer.putInt(this.userId); buffer.flip(); byte[] result = new byte[buffer.remaining()]; //將緩衝區的字節傳輸給指定的result目標數組中 buffer.get(result); return result; } }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * @FileName SerializableTest.java * @Description: * * @Date 2016年3月5日 * @author Administroter * @version 1.0 * */ public class SerializableTest { public static void main(String[] args) throws IOException{ //實例化Person對象 Person person = new Person(); //對象賦值 person.buildUserID(1).buildUserName("張三"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); //ByteArrayOutputStream轉對象輸出流 ObjectOutputStream os = new ObjectOutputStream(bos); //由於序列化是基於字節的,調用ObjectOutputStream的writeObject方法將對象序列化 os.writeObject(person); os.flush(); os.close(); byte[] b = bos.toByteArray(); System.out.println("基於java序列化後對象byte數組的大小:" + b.length); bos.close(); System.out.println("基於二進制編碼後byte數組的大小" + person.codeC().length); } }
測試結果:編程
從上面的結果來看,基於JDK的對象序列化性能遠遠小於傳統二進制編碼對象,那麼在咱們的通信網絡編程中,咱們又該怎麼傳遞對象呢,下一節咱們再來討論數組