Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement the fastGetObjectMap to get better read performance #845

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions benchmarks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@
<version>${jmh.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.9.4</version>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package com.esotericsoftware.kryo.benchmarks.io;
theigl marked this conversation as resolved.
Show resolved Hide resolved

import com.esotericsoftware.kryo.util.CuckooObjectMap;

import com.esotericsoftware.kryo.util.FastGetObjectMap;
import com.esotericsoftware.kryo.util.ObjectMap;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

// mvn -f benchmarks/pom.xml compile exec:java -Dexec.args="-f 3 -wi 6 -i 3 -t 2 -w 2s -r 2 FastGetObjectMapBenchmark.read"
public class FastGetObjectMapBenchmark {

@Benchmark
public void read (ReadBenchmarkState state, Blackhole blackhole) {
state.read(blackhole);
}

@Benchmark
public void write (BenchmarkState state, Blackhole blackhole) {
state.write(blackhole);
}

@Benchmark
public void writeRead (BenchmarkState state, Blackhole blackhole) {
state.readWrite(blackhole);
}

@State(Scope.Thread)
public static class AbstractBenchmarkState {
@Param({"100"}) public int numClasses;
@Param({"2048"}) public int maxCapacity;
@Param({"fastGet", "cuckoo"}) public MapType mapType;

MapAdapter<Object, Integer> map;
List<? extends Class<?>> classes;
}

@State(Scope.Thread)
public static class BenchmarkState extends AbstractBenchmarkState {

@Setup(Level.Trial)
public void setup () {
map = createMap(mapType, maxCapacity);
classes = IntStream.rangeClosed(0, numClasses).mapToObj(FastGetObjectMapBenchmark::buildClass)
.collect(Collectors.toList());
}

public void write (Blackhole blackhole) {
classes.stream()
.map(c -> map.put(c, 1))
.forEach(blackhole::consume);
}

public void readWrite (Blackhole blackhole) {
classes.forEach(c -> map.put(c, 1));
Collections.shuffle(classes);

final Random random = new Random();
for (int i = 0; i < numClasses; i++) {
final Class<?> key = classes.get(random.nextInt(numClasses - 1));
blackhole.consume(map.get(key));
}

map.clear();
}
}

@State(Scope.Thread)
public static class ReadBenchmarkState extends AbstractBenchmarkState {

@Setup(Level.Trial)
public void setup () {
map = createMap(mapType, maxCapacity);
classes = IntStream.rangeClosed(0, numClasses).mapToObj(FastGetObjectMapBenchmark::buildClass)
.collect(Collectors.toList());
classes.forEach(c -> map.put(c, 1));
Collections.shuffle(classes);
}

public void read (Blackhole blackhole) {
classes.stream()
.limit(500)
.map(map::get)
.forEach(blackhole::consume);
}
}

public enum MapType {
cuckoo, fastGet
}


interface MapAdapter<K, V> {
V get (K key);

V put (K key, V value);

void clear();
}

private static MapAdapter<Object, Integer> createMap (MapType mapType, int maxCapacity) {
switch (mapType) {
case fastGet:
return new ObjectMapAdapter<>(new FastGetObjectMap<>(), maxCapacity);
case cuckoo:
return new CuckooMapAdapter<>(new CuckooObjectMap<>(), maxCapacity);
default:
throw new IllegalStateException("Unexpected value: " + mapType);
}
}

static class CuckooMapAdapter<K> implements MapAdapter<K, Integer> {
private final CuckooObjectMap<K, Integer> delegate;
private final int maxCapacity;

public CuckooMapAdapter (CuckooObjectMap<K, Integer> delegate, int maxCapacity) {
this.delegate = delegate;
this.maxCapacity = maxCapacity;
}

@Override
public Integer get (K key) {
return delegate.get(key, -1);
}

@Override
public Integer put (K key, Integer value) {
delegate.put(key, value);
return null;
}

@Override
public void clear() {
delegate.clear(maxCapacity);
}

}

static class ObjectMapAdapter<K> implements MapAdapter<K, Integer> {
private final ObjectMap<K, Integer> delegate;
private final int maxCapacity;

public ObjectMapAdapter (ObjectMap<K, Integer> delegate, int maxCapacity) {
this.delegate = delegate;
this.maxCapacity = maxCapacity;
}

@Override
public Integer get (K key) {
return delegate.get(key, -1);
}

@Override
public Integer put (K key, Integer value) {
delegate.put(key, value);
return null;
}

@Override
public void clear() {
delegate.clear(maxCapacity);
}

}

private static class HashMapAdapter<K> implements MapAdapter<K, Integer> {
private final HashMap<K, Integer> delegate;

public HashMapAdapter (HashMap<K, Integer> delegate) {
this.delegate = delegate;
}

@Override
public Integer get (K key) {
return delegate.get(key);
}

@Override
public Integer put (K key, Integer value) {
return delegate.put(key, value);
}

@Override
public void clear() {
delegate.clear();
}
}

private static Class<?> buildClass (int i) {
return new ByteBuddy()
.subclass(Object.class)
.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value(String.valueOf(i)))
.make()
.load(FastGetObjectMapBenchmark.class.getClassLoader())
.getLoaded();
}




}
3 changes: 1 addition & 2 deletions src/com/esotericsoftware/kryo/util/DefaultClassResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ public class DefaultClassResolver implements ClassResolver {
protected Kryo kryo;

protected final IntMap<Registration> idToRegistration = new IntMap<>();
protected final CuckooObjectMap<Class, Registration> classToRegistration = new CuckooObjectMap<>();

protected final FastGetObjectMap<Class, Registration> classToRegistration = new FastGetObjectMap<>();
protected IdentityObjectIntMap<Class> classToNameId;
protected IntMap<Class> nameIdToClass;
protected ObjectMap<String, Class> nameToClass;
Expand Down
92 changes: 92 additions & 0 deletions src/com/esotericsoftware/kryo/util/FastGetObjectMap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/* Copyright (c) 2008-2020, Nathan Sweet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

package com.esotericsoftware.kryo.util;

/**
* this map extends from objectMap, optimized for better reading performance
* so there will be some tricky optimization
* **/
public class FastGetObjectMap<K, V> extends ObjectMap<K, V> {
/** Creates a new map with an initial capacity of 51 and a load factor of 0.8. */
public FastGetObjectMap () {
this(51, 0.8f);
}

/** Creates a new map with a load factor of 0.8.
* @param initialCapacity If not a power of two, it is increased to the next nearest power of two. */
public FastGetObjectMap (int initialCapacity) {
this(initialCapacity, 0.8f);
}

/** Creates a new map with a load factor of 0.8.
* @param initialCapacity If not a power of two, it is increased to the next nearest power of two. */
public FastGetObjectMap (int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}

/** Returns the value for the specified key, or null if the key is not in the map.
* unroll because of better performance (benchmark shows about 2% higher performance)
* */
@Override
@Null
public <T extends K> V get (T key) {
K[] keyTable = this.keyTable;
for (int i = place(key);; i = i + 1 & mask) {
K other = keyTable[i];
if (key.equals(other)) return valueTable[i]; // Same key was found.
if (other == null) return null; // Empty space is available.
}
}

@Override
/** Returns the value for the specified key, or the default value if the key is not in the map.
* unroll because of better performance
* */
public V get (K key, @Null V defaultValue) {
K[] keyTable = this.keyTable;
for (int i = place(key);; i = i + 1 & mask) {
K other = keyTable[i];
if (key.equals(other)) return valueTable[i]; // Same key was found.
if (other == null) return defaultValue; // Empty space is available.
}
}

/**
* 1. remove magic number so that minimize the computation cost
* 2. with low loadFactor, we don't need to consider the hash collision **/
@Override
protected int place (K item) {
return item.hashCode() & mask;
}

/* According to previous benchmark, different size have different best loadFactor **/
@Override
protected float computeLoadFactor(int newSize){
theigl marked this conversation as resolved.
Show resolved Hide resolved
if(newSize <= 2048){
return 0.7f;
}else{
return 0.5f;
}
}
}




11 changes: 9 additions & 2 deletions src/com/esotericsoftware/kryo/util/ObjectMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public class ObjectMap<K, V> implements Iterable<ObjectMap.Entry<K, V>> {

public int size;

K[] keyTable;
V[] valueTable;
protected K[] keyTable;
theigl marked this conversation as resolved.
Show resolved Hide resolved
protected V[] valueTable;

float loadFactor;
int threshold;
Expand Down Expand Up @@ -295,9 +295,16 @@ public void ensureCapacity (int additionalCapacity) {
int tableSize = tableSize(size + additionalCapacity, loadFactor);
if (keyTable.length < tableSize) resize(tableSize);
}

/**
* Subclass override to dynamically adjust loadFactor, get better performance. */
protected float computeLoadFactor(int newSize){
theigl marked this conversation as resolved.
Show resolved Hide resolved
return loadFactor;
}

final void resize (int newSize) {
int oldCapacity = keyTable.length;
loadFactor = computeLoadFactor(newSize);
threshold = (int)(newSize * loadFactor);
mask = newSize - 1;
shift = Long.numberOfLeadingZeros(mask);
Expand Down