TECHSCOREにあるNewIOを勉強してみた。
http://www.techscore.com/tech/J2SE/NIO/answer/1-1.html
結果は、下のような感じです。
ダイレクトバッファの方が高速なのではなかったっけ?
100 ダイレクト 0msec 1000 ダイレクト 0msec 10000 ダイレクト 32msec 100000 ダイレクト 203msec 1000000 ダイレクト 1953msec 100 非ダイレクト 0msec 1000 非ダイレクト 0msec 10000 非ダイレクト 16msec 100000 非ダイレクト 171msec 1000000 非ダイレクト 1516msec
使ったコードは以下。
package jp.person.suto; public class NewIOTest1Main { public static void main(String[] args) { BufferTestSample sample = new BufferTestSample(); int[] sizes = {100, 1000, 10000, 100000, 1000000}; sample.doAllTime(sizes, true); sample.doAllTime(sizes, false); } }
package jp.person.suto; import java.nio.ByteBuffer; import java.nio.IntBuffer; public class BufferTestSample { public void doAllTime(int[] sizes, boolean isDirect) { for (int idx = 0; idx < sizes.length; idx++) { doOneTime(sizes[idx], isDirect); } } public void doOneTime(int size, boolean isDirect) { long start = System.currentTimeMillis(); for (int cnt = 0; cnt < 100; cnt++) { doExecute(size, isDirect); } long end = System.currentTimeMillis(); printResult(size, isDirect, start, end); } private void doExecute(int size, boolean isDirect) { IntBuffer buffer = makeBuffer(size, isDirect); for (int cnt2 = 0; cnt2 < size; cnt2++) { buffer.put(cnt2, cnt2); } int[] ints; boolean result = true; try { ints = buffer.array(); } catch (UnsupportedOperationException ex) { // System.out.print(ex.getMessage()); result = false; } // if (result == true) // { // System.out.print("OK!"); // } } private void printResult(int size, boolean isDirect, long start, long end) { String bufferKind = isDirect ? "ダイレクト" : "非ダイレクト"; StringBuilder str = new StringBuilder(); str.append(size); str.append("\t"); str.append(bufferKind); str.append("\t"); str.append(end - start); str.append("msec"); System.out.println(str.toString()); } private IntBuffer makeBuffer(int size, boolean isDirect) { IntBuffer buffer; if (isDirect == true) { buffer = ByteBuffer.allocateDirect(size * 4).asIntBuffer(); } else { buffer = IntBuffer.allocate(size); } return buffer; } }