Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java native HashMap in clojure run slowly?

I associate a key to a hash map for 10000000 time. Here's the Java code and output:

import java.util.HashMap;

public class TestMap {
    public static void main(String[] args) {
        HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
        long  start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            mp.put(1, 1);
        }
        long end = System.currentTimeMillis();
        System.out.println("Elapsed time: " + (end - start) + " msecs");
    }
}


$ javac TestMap.java && java -cp . TestMap
Elapsed time: 38 msecs

And then I call java from clojure in REPL:

user=> (import java.util.HashMap)
java.util.HashMap
user=> (def mp (HashMap.))
#'user/mp
user=>  (time (dotimes [n 10000000] (.put mp 1 1)))
"Elapsed time: 10024.797 msecs"
nil

Both code do the same thing, but the clojure version runs exstreamly slow!!

What's the problem?

like image 508
qiuxiafei Avatar asked Jun 29 '12 02:06

qiuxiafei


1 Answers

add type hint is better:

user> (import 'java.util.HashMap)
java.util.HashMap
user> (def mp (HashMap.))
#'user/mp
user> (time (dotimes [n 10000000] (.put mp 1 1)))
"Elapsed time: 13932.248126 msecs"
nil
user> (time (dotimes [n 10000000] (.put ^HashMap mp 1 1)))
"Elapsed time: 117.915992 msecs"
nil
like image 93
number23_cn Avatar answered Sep 24 '22 01:09

number23_cn