import java.io.Serializable; import java.nio.ByteBuffer; public class UserInfo implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] codeC() { ByteBuffer buffer = ByteBuffer.allocate(1024); byte[] value = this.name.getBytes(); buffer.putInt(value.length); buffer.put(value); buffer.putLong(this.id); buffer.flip(); byte[] result = new byte[buffer.remaining()]; buffer.get(result); return result; } public byte[] codeC(ByteBuffer buffer) { buffer.clear(); byte[] value = this.name.getBytes(); buffer.putInt(value.length); buffer.put(value); buffer.putLong(this.id); buffer.flip(); byte[] result = new byte[buffer.remaining()]; buffer.get(result); return result; } }
import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; public class MainTest { public static void main(String[] args) throws Exception { UserInfo info = new UserInfo(); info.setId(1L); info.setName("Tom"); int loop = 100_0000; ByteArrayOutputStream bout = null; ObjectOutputStream out = null; long start = System.currentTimeMillis(); for (int i = 0; i < loop; i ) { bout = new ByteArrayOutputStream(); out = new ObjectOutputStream(bout); out.flush(); out.close(); byte[] b = bout.toByteArray(); bout.close(); } System.out.println("jdk serializable time : " (System.currentTimeMillis() - start) " ms"); System.out.println("------------------------------"); start = System.currentTimeMillis(); ByteBuffer buffer = ByteBuffer.allocate(1024); for (int i = 0; i < loop; i ) { byte[] bytes = info.codeC(buffer); } System.out.println("ByteBuffer time : " (System.currentTimeMillis() - start) " ms"); } }
import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; public class MainTest { public static void main(String[] args) throws Exception { UserInfo info = new UserInfo(); info.setId(1L); info.setName("Tom"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(info); out.flush(); out.close(); byte[] b = bout.toByteArray(); System.out.println("jdk serializable: " b.length); bout.close(); System.out.println("ByteBuffer : " info.codeC().length); } }
END 十期推荐 【271期】面试官:Spring MVC的处理流程是怎样的? 【272期】数据结构:哈希表原理以及面试中的常见考点 【273期】告诉面试官,我能优化groupBy,而且知道得很深! 【274期】面试官:怎么保证缓存和数据库一致性 【275期】面试官:你对MySQL中的索引了解多少? 【276期】面试官:你分析过@Annotation注解的实现原理吗? 【277期】面试官:说几种常用的分布式 ID 解决方案 【278期】面试官:都说 select * 效率低下,你知道什么原因吗? 【279期】面试官:Java遍历Map集合有哪几种方式?各自效率怎么样? 【280期】k8s面试问什么? ? ~