Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: why Array (w index) *order of magnitude* faster than Map (key) access?
    primarykey
    data
    text
    <p>We ran the attached test. The results consistently show that access via Array by index is 10x faster than access via Map by key. This order of magnitude difference surprised us.</p> <p>Our key for the Map is java.lang.String ... is the cost of computing the Map key's java.lang.String.hashcode() implementation the exclusive reason? in the attached code, I exercised using only one key </p> <pre><code>java.lang.String key = 1; </code></pre> <p>Doesn't the compiler/runtime cache in this case? Or does it recompute on every invoke?</p> <p>Thanks for any insights.</p> <pre><code>public class PerfTest { static java.util.HashMap&lt;String, Double&gt; map; static Double[] array = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0}; static long nTimes = 1000000; static{ map = new java.util.HashMap&lt;String, Double&gt;(); map.put("1", new Double(1)); map.put("2", new Double(2)); map.put("3", new Double(3)); map.put("4", new Double(4)); map.put("5", new Double(5)); map.put("6", new Double(6)); map.put("7", new Double(7)); map.put("8", new Double(8)); map.put("9", new Double(9)); map.put("10", new Double(10)); } public static void main(String[] args){ PerfTest tester = new PerfTest(); long timeInMap = tester.testHashMap(); long timeInArray = tester.testArray(); System.out.println("Corrected time elapsed in map(in seconds): " + (timeInMap)/1000000000.0); System.out.println("Corrected time elapsed in array(in seconds): " + (timeInArray)/1000000000.0); } private long testHashMap(){ int sz = map.size(); long startTime = System.nanoTime(); String key = "1"; for (int i=0; i &lt;nTimes; i++){ double sum = 0; for (int j =1; j&lt;=sz; j++){ sum += map.get(key); } } return (System.nanoTime() - startTime); } private long testArray(){ long startTime = System.nanoTime(); for (int i=0; i &lt;nTimes; i++){ double sum = 0; for (int j=0; j&lt; array.length; j++) { sum += array[j]; } } return (System.nanoTime() - startTime); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload