UserInfo implements Serializable { public byte[] codeC(){ ByteBuffer buffer = ByteBuffer.allocate(1024); byte[] value = this.userName.getBytes(); buffer.putInt(value.length); buffer.put(value); buffer.putInt(this.userId); buffer.flip(); byte[] result = new byte[buffer.remaining()]; buffer.get(result); return result; } UserInfo();  UserInfo(int userId, String userName); String getUserName(); void setUserName(String userName); int getUserId(); void setUserId(int userId); byte[] codeC();  }
@Test public void codeC() throws Exception { UserInfo info = new UserInfo(20, "wuhulala"); byte[] b = jdkCodeC(info); System.out.println("jdk serializable length is : " + b.length); printSeparator(); System.out.println("custom serializable length is : " + info.codeC().length); }
@Test public void testCodeCSpeed() throws IOException { UserInfo info = new UserInfo(20, "wuhulala"); int loop = 1000000; StopWatcher w1 = new StopWatcher(); byte[] b1 = new byte[0]; for (int i = 0; i < loop; i++) { b1 = jdkCodeC(info); } long elapsed1 = w1.elapsedTime(); System.out.println("jdk cost time is :" + elapsed1 + "ms" + ", cost space is : " + b1.length); printSeparator(); printSeparator(); StopWatcher w2 = new StopWatcher(); byte[] b2 = new byte[0]; for (int i = 0; i < loop; i++) { b2 = info.codeC(); } long elapsed2 = w2.elapsedTime(); System.out.println("custom cost time is :" + elapsed2 + "ms" + ", cost space is : " + b2.length); printSeparator(); printSeparator(); StopWatcher w3 = new StopWatcher(); byte[] b3 = new byte[0]; MessagePack msgPack = new MessagePack(); for (int i = 0; i < loop; i++) { b3 = msgPack(msgPack, info); } long elapsed3 = w3.elapsedTime(); System.out.println("messagePack cost time is :" + elapsed3 + "ms"+ ", cost space is : " + b3.length); }