package blogindex.test; import java.io.*; import java.nio.*; import java.util.*; public class Test6 { static double total = 2000000; public static void stats( long before, long after ) { long used = (after-before); System.out.printf( "total: %,d\n", used ); System.out.printf( "per key: %f\n", used / total ); } public static void test1() { System.out.println( "test1:" ); Runtime r = Runtime.getRuntime(); System.gc(); long before = r.totalMemory() - r.freeMemory(); //ByteBuffer buff = new ByteBuffer(); Map test = new TreeMap(); int prefix = 10000000; for( int i = 0; i < total; ++i ) { String key = "" + (prefix + i); test.put( key, i ); } System.gc(); long after = r.totalMemory() - r.freeMemory(); stats( before, after ); } public static void test2() { System.out.println( "test2:" ); Runtime r = Runtime.getRuntime(); System.gc(); long before = r.totalMemory() - r.freeMemory(); //ByteBuffer buff = new ByteBuffer(); Map test = new TreeMap(); int prefix = 10000000; for( int i = 0; i < total; ++i ) { String key = "" + (prefix + i); test.put( new ByteArrayKey( key.getBytes() ), i ); } System.gc(); long after = r.totalMemory() - r.freeMemory(); stats( before, after ); } public static void main( String[] args ) throws Throwable { test1(); test1(); test1(); test2(); } } class ByteArrayKey implements Comparable { byte[] data; public ByteArrayKey( byte[] data ) { this.data = data; } public int hashCode() { int v = 0; for( int i = 0; i < data.length; ++i ) { v += (int)data[i]; } return v; } public boolean equals( Object obj ) { ByteArrayKey b = (ByteArrayKey)obj; return Arrays.equals( data, b.data ); } public int compareTo(Object o) { ByteArrayKey b = (ByteArrayKey)o; for( int i = 0; i < data.length; ++i ) { if ( b.data.length < i ) return -1; if ( data[i] < b.data[i] ) return -1; if ( data[i] > b.data[i] ) return 1; if ( data[i] == b.data[i] ) { //we're not done with the strings yet. if ( i < data.length - 1 ) continue; return 0; } } //only used if the comparing object is actually larger. return 1; } }