Skip to content

Instantly share code, notes, and snippets.

@EliasZ
Created April 15, 2023 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EliasZ/29edd8101024b1beacaff1797bd283e0 to your computer and use it in GitHub Desktop.
Save EliasZ/29edd8101024b1beacaff1797bd283e0 to your computer and use it in GitHub Desktop.
optional benchmark
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Optional;
public class OptionalBenchmark {
private record DataObject(String someField) {
}
private static final char STATUS_IF_SOME_FIELD_EXISTS = 'A';
private static final char STATUS_IF_SOME_FIELD_IS_MISSING = 'B';
@State(Scope.Thread)
public static class DataObjectState {
final DataObject dataObjectWithNullField = new DataObject(null);
final DataObject dataObjectWithNonNullField = new DataObject("abc");
}
@Benchmark
public void withOptionalNull(final Blackhole blackhole, final DataObjectState state) {
final Character result = Optional.ofNullable(state.dataObjectWithNullField.someField)
.map(someField -> STATUS_IF_SOME_FIELD_EXISTS)
.orElse(STATUS_IF_SOME_FIELD_IS_MISSING);
blackhole.consume(result);
}
@Benchmark
public void withOptionalNonNull(final Blackhole blackhole, final DataObjectState state) {
final Character result = Optional.ofNullable(state.dataObjectWithNonNullField.someField)
.map(someField -> STATUS_IF_SOME_FIELD_EXISTS)
.orElse(STATUS_IF_SOME_FIELD_IS_MISSING);
blackhole.consume(result);
}
@Benchmark
public void withTernaryNull(final Blackhole blackhole, final DataObjectState state) {
final Character result = state.dataObjectWithNullField.someField == null
? STATUS_IF_SOME_FIELD_IS_MISSING
: STATUS_IF_SOME_FIELD_EXISTS;
blackhole.consume(result);
}
@Benchmark
public void withTernaryNonNull(final Blackhole blackhole, final DataObjectState state) {
final Character result = state.dataObjectWithNonNullField.someField == null
? STATUS_IF_SOME_FIELD_IS_MISSING
: STATUS_IF_SOME_FIELD_EXISTS;
blackhole.consume(result);
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(OptionalBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment