1 /*
   2  * Copyright (c) 2018, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  */
  22 
  23 package org.openjdk.bench.java.util;
  24 
  25 import org.openjdk.jmh.annotations.Benchmark;
  26 import org.openjdk.jmh.annotations.BenchmarkMode;
  27 import org.openjdk.jmh.annotations.Mode;
  28 import org.openjdk.jmh.annotations.OutputTimeUnit;
  29 import org.openjdk.jmh.annotations.Scope;
  30 import org.openjdk.jmh.annotations.Setup;
  31 import org.openjdk.jmh.annotations.State;
  32 
  33 import java.util.HashMap;
  34 import java.util.Map;
  35 import java.util.Random;
  36 import java.util.concurrent.TimeUnit;
  37 import java.util.stream.IntStream;
  38 
  39 import static java.util.stream.Collectors.toMap;
  40 
  41 @BenchmarkMode(Mode.AverageTime)
  42 @OutputTimeUnit(TimeUnit.MILLISECONDS)
  43 @State(Scope.Thread)
  44 public class HashMapBench {
  45     private Map<Integer, Integer> bigMapToAdd;
  46     private Random r;
  47 
  48     @Setup
  49     public void setup() {
  50         this.r = new Random();
  51         this.bigMapToAdd = IntStream.range(0, 1_000_000).boxed().collect(toMap(i -> 7 + i * 128, i -> r.nextInt()));
  52     }
  53 
  54     @Benchmark
  55     public int putAllWithBigMapToNonEmptyMap() {
  56         var map = new HashMap<Integer, Integer>();
  57         map.put(-1, -1);
  58         map.putAll(bigMapToAdd);
  59         return map.size();
  60     }
  61 
  62     @Benchmark
  63     public int putAllWithBigMapToEmptyMap() {
  64         var map = new HashMap<Integer, Integer>();
  65         map.putAll(bigMapToAdd);
  66         return map.size();
  67     }
  68 
  69     @Benchmark
  70     public int put() {
  71         var map = new HashMap<Integer, Integer>();
  72         for (int k : bigMapToAdd.keySet()) {
  73             map.put(k, bigMapToAdd.get(k));
  74         }
  75         return map.size();
  76     }
  77 }