Last active
August 29, 2015 14:16
-
-
Save jcsahnwaldt/f904de89a4440a1b0458 to your computer and use it in GitHub Desktop.
Microbenchmark: Convert list to map with or without streams / lambdas. Result: Performance is the same. See https://stackoverflow.com/questions/674639/scala-best-way-of-turning-a-collection-into-a-map-by-key/3249462#comment46124673_3249462
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
import java.util.*; | |
import java.util.stream.*; | |
import static java.util.stream.Collectors.*; | |
import java.util.function.*; | |
class Value { | |
private final String key; | |
public Value(String key) { | |
this.key = key; | |
} | |
public String key() { | |
return this.key; | |
} | |
} | |
class RandomStrings { | |
private final Random rnd; | |
private final char[] symbols; | |
private char[] buffer; | |
public RandomStrings(char[] symbols, long seed) { | |
if (symbols == null) throw new NullPointerException("symbols"); | |
this.symbols = symbols; | |
this.rnd = new Random(seed); | |
} | |
public String nextString(int length) { | |
if (buffer == null || length > buffer.length) buffer = new char[length]; | |
for (int i = 0; i < length; i++) { | |
buffer[i] = symbols[rnd.nextInt(symbols.length)]; | |
} | |
return new String(buffer); | |
} | |
} | |
public class ToMap { | |
private static final int S = 500000; | |
private static final int C = 20; | |
private static final int N = 20; | |
private static final char[] symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-".toCharArray(); | |
public static void main(String[] args) throws Exception { | |
RandomStrings rnd = new RandomStrings(symbols, 1234L); | |
List<Value> values = new ArrayList<>(S); | |
for (int i = 0; i < S; i++) values.add(new Value(rnd.nextString(20))); | |
long total = System.nanoTime(); | |
for (int c = 0; c < C; c++) { | |
long nanos = System.nanoTime(); | |
for (int n = 0; n < N; n++) { | |
if (1 == 0) proc(values); | |
else func(values); | |
} | |
nanos = System.nanoTime() - nanos; | |
System.out.println("millis: " + nanos / 1000000F / N); | |
} | |
total = System.nanoTime() - total; | |
System.out.println("total: " + total / 1000000F / N / C); | |
} | |
private static Map<String, Value> proc(List<Value> values) { | |
Map<String, Value> map = new HashMap<>(values.size() * 4 / 3); | |
for (Value value: values) map.put(value.key(), value); | |
return map; | |
} | |
private static Map<String, Value> func(List<Value> values) { | |
return values.stream().collect(toMap(v -> v.key(), v -> v, (u,v) -> { throw new IllegalStateException(); }, () -> new HashMap<>(values.size() * 4 / 3))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment