标签:
StringBuilder sb = new StringBuilder(1024); //向sb中写入900个左右的随机字符内容 for(int j=1; j< 50;j++) { sb.append(Math.random()); } //System.out.println("sb:" + sb.length()); long startTime = System.currentTimeMillis(); for(int i=0;i<10000;i++) { /* byte[] data = sb.toString().getBytes(); ByteBuffer buffer = ByteBuffer.allocate(data.length); buffer.put(data); buffer.flip(); */ //下面这段代码代替上面注释掉的4行代码,并且效率稍微还高一点 ByteBuffer buffer = ByteBuffer.wrap(sb.toString().getBytes()); } System.out.println("time:" + (System.currentTimeMillis() - startTime));
通过查看ByteBuffer.java源代码,主要看一下 wrap()和allocate()两个方法的具体实现。
当根据一个byte[]来生成一个固定的ByteBuffer时,使用ByteBuffer.wrap()非法的合适。
以前都是通过上面的4行代码来完成,看了一下源代码,还是使用wrap()来的省事。
2013-01-12
ByteBuffer: 当由一个byte[]来生成一个固定不变的ByteBuffer时,使用ByteBuffer.wrap(byte[]);
标签:
原文地址:http://www.cnblogs.com/personnel/p/4584832.html