Skip to content

Instantly share code, notes, and snippets.

@tlinkowski
Last active December 8, 2018 20:14
Show Gist options
  • Save tlinkowski/240784b9e249e83b58e0c522efec097f to your computer and use it in GitHub Desktop.
Save tlinkowski/240784b9e249e83b58e0c522efec097f to your computer and use it in GitHub Desktop.
TransformerBenchmark
plugins {
// https://github.com/melix/jmh-gradle-plugin
id 'me.champeau.gradle.jmh' version '0.4.7'
}
wrapper {
gradleVersion = '5.0'
}
apply plugin: 'java'
sourceCompatibility = 1.8
package pl.tlinkowski.transformer;
import java.util.function.Function;
/**
* @author Tomasz Linkowski
*/
final class StringBox implements Transformable {
private final String string;
StringBox(String string) {
this.string = string;
}
StringBox toLowerCase() {
return new StringBox(string.toLowerCase());
}
@Override
public Transformer<StringBox> transformed() {
return this::transform;
}
<R> R transform(Function<? super StringBox, ? extends R> f) {
return f.apply(this);
}
}
package pl.tlinkowski.transformer;
/**
* @author Tomasz Linkowski
*/
public interface Transformable {
Transformer<?> transformed();
}
package pl.tlinkowski.transformer;
import java.util.function.Function;
/**
* @author Tomasz Linkowski
*/
@FunctionalInterface
public interface Transformer<T> {
<R> R by(Function<? super T, ? extends R> f);
}
package pl.tlinkowski.transformer;
import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;
/**
* @author Tomasz Linkowski
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class TransformerBenchmark {
@Param({"no change", "Some Change"})
public String string;
public StringBox stringBox;
@Setup
public void setup() {
stringBox = new StringBox(string);
}
@Benchmark
public StringBox baseline() {
return stringBox.toLowerCase();
}
@Benchmark
public StringBox transform() {
return stringBox.transform(StringBox::toLowerCase);
}
@Benchmark
public StringBox transformed() {
return stringBox.transformed().by(StringBox::toLowerCase);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment