Created
February 27, 2015 04:58
-
-
Save tatumizer/054124df0b73dec4f9f5 to your computer and use it in GitHub Desktop.
java version of map benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package javabench; | |
import java.util.HashMap; | |
import java.util.Map; | |
// test other map types | |
//import java.util.LinkedHashMap; | |
//import java.util.TreeMap; | |
//import java.util.concurrent.ConcurrentHashMap; | |
public class MapTest { | |
final static int ITERATIONS=1000000; | |
final static String[] randomStrings=new String[]{ | |
"0000000000","1111111111","222222222","3333333333","4444444444","5555555555","6666666666","7777777777", | |
"8888888888","9999999999","aaaaaaaaaa","bbbbbbbbbb","ccccccccc","dddddddddd","eeeeeeeeee","ffffffffff" | |
}; | |
final static String[] randomStringsCopy=new String[randomStrings.length]; | |
static { | |
for (int i=0; i<randomStrings.length; i++) { | |
randomStringsCopy[i]=randomStrings[i].substring(0,1)+randomStrings[i].substring(1); | |
} | |
} | |
static int testMap(int size) { | |
int x=0; | |
for (int i=0; i<ITERATIONS; i++) { | |
Map<String,Integer> map=new HashMap<>(); // try also LinkedHashMap, TreeMap etc | |
for (int j=0; j<size; j++) { | |
map.put(randomStrings[j],j); | |
} | |
for (int j=0; j<size; j++) { | |
x|=map.get(randomStrings[j]); // !!! try change to randomStrings1 - get different timing | |
} | |
} | |
return x; | |
} | |
static void run(int size) { | |
int x=0; | |
long time=0; // saving result to print, to make sure nothing is optimized away miraculously | |
for (int i=0; i<3; i++) { | |
long start=System.currentTimeMillis(); | |
x=testMap(size); | |
time=System.currentTimeMillis()-start; | |
} | |
System.out.println("Java HashMap" +" size="+size +" elapsed time="+time+" milliseconds => "+ | |
(1000000.0*time/(ITERATIONS*2*size))+" nanoseconds/operation "+" result="+x); | |
} | |
public static void main(String[] arg) { | |
for (int size: new int[]{6,8,10,12,14,16}) { | |
run(size); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment