【问题标题】:Why Java Optional performance increase with number of chained calls?为什么 Java Optional 的性能会随着链接调用的数量而增加?
【发布时间】:2017-11-13 21:36:02
【问题描述】:

最近有人问我 java 8 Optional 的性能。经过一番搜索,我找到了this question 和几篇博文,答案相互矛盾。所以我使用JMH 对其进行了基准测试,但我不明白我的发现。

这是我的基准代码的要点(full code 可在 GitHub 上找到):

@State(Scope.Benchmark)
public class OptionalBenchmark {

  private Room room;

  @Param({ "empty", "small", "large", "full" })
  private String filling;

  @Setup
  public void setUp () {
    switch (filling) {
      case "empty":
        room = null;
        break;
      case "small":
        room = new Room(new Flat(new Floor(null)));
        break;
      case "large":
        room = new Room(new Flat(new Floor(new Building(new Block(new District(null))))));
        break;
      case "full":
        room = new Room(new Flat(new Floor(new Building(new Block(new District(new City(new Country("France"))))))));
        break;
      default:
        throw new IllegalStateException("Unsupported filling.");
    }
  }

  @Benchmark
  public String nullChecks () {
    if (room == null) {
      return null;
    }

    Flat flat = room.getFlat();
    if (flat == null) {
      return null;
    }

    Floor floor = flat.getFloor();
    if (floor == null) {
      return null;
    }

    Building building = floor.getBuilding();
    if (building == null) {
      return null;
    }

    Block block = building.getBlock();
    if (block == null) {
      return null;
    }

    District district = block.getDistrict();
    if (district == null) {
      return null;
    }

    City city = district.getCity();
    if (city == null) {
      return null;
    }

    Country country = city.getCountry();
    if (country == null) {
      return null;
    }

    return country.getName();
  }

  @Benchmark
  public String optionalsWithMethodRefs () {
    return Optional.ofNullable (room)
        .map (Room::getFlat)
        .map (Flat::getFloor)
        .map (Floor::getBuilding)
        .map (Building::getBlock)
        .map (Block::getDistrict)
        .map (District::getCity)
        .map (City::getCountry)
        .map (Country::getName)
        .orElse (null);
  }

  @Benchmark
  public String optionalsWithLambdas () {
    return Optional.ofNullable (room)
        .map (room -> room.getFlat ())
        .map (flat -> flat.getFloor ())
        .map (floor -> floor.getBuilding ())
        .map (building -> building.getBlock ())
        .map (block -> block.getDistrict ())
        .map (district -> district.getCity ())
        .map (city -> city.getCountry ())
        .map (country -> country.getName ())
        .orElse (null);
  }

}

我得到的结果是:

Benchmark                                  (filling)   Mode  Cnt           Score         Error  Units
OptionalBenchmark.nullChecks                   empty  thrpt  200   468835378.093 ±  895576.864  ops/s
OptionalBenchmark.nullChecks                   small  thrpt  200   306602013.907 ±  136966.520  ops/s
OptionalBenchmark.nullChecks                   large  thrpt  200   259996142.619 ±  307584.215  ops/s
OptionalBenchmark.nullChecks                    full  thrpt  200   275954974.981 ± 4154597.959  ops/s
OptionalBenchmark.optionalsWithLambdas         empty  thrpt  200   460491457.335 ±  322920.650  ops/s
OptionalBenchmark.optionalsWithLambdas         small  thrpt  200    98604468.453 ±   68320.074  ops/s
OptionalBenchmark.optionalsWithLambdas         large  thrpt  200    67648427.470 ±  206810.285  ops/s
OptionalBenchmark.optionalsWithLambdas          full  thrpt  200   167124820.392 ± 1229924.561  ops/s
OptionalBenchmark.optionalsWithMethodRefs      empty  thrpt  200   460690135.554 ±  273853.568  ops/s
OptionalBenchmark.optionalsWithMethodRefs      small  thrpt  200    98639064.680 ±   56848.805  ops/s
OptionalBenchmark.optionalsWithMethodRefs      large  thrpt  200    68138436.113 ±  158409.539  ops/s
OptionalBenchmark.optionalsWithMethodRefs       full  thrpt  200   169603006.971 ±   52646.423  ops/s

首先,当给定一个空引用时,可选和空检查的行为几乎相同。我猜这是因为Optional.empty () 只有一个实例,所以任何对它的.map () 方法调用都会返回自身。

但是,当给定对象为非 null 且包含非 null 属性链时,必须在每次调用 .map () 时实例化一个新的 Optional。因此,性能下降的速度比空检查快得多。说得通。期待我的full加注,那里的性能一下子提升。那么这里发生了什么魔法呢?我在基准测试中做错了吗?

编辑

我第一次运行的参数是 JMH 的默认参数:每个基准测试在 10 个不同的分支中运行,每个分支进行 20 次 1 秒的预热迭代,然后每个 1 秒的 20 次测量迭代。我相信这些价值是理智的,因为我相信我使用的图书馆。然而,由于我被告知我没有足够的热身,这里是一个更长的测试的结果(200 次热身迭代和 10 个前叉中的每一个的 200 次测量迭代):

# JMH version: 1.19
# VM version: JDK 1.8.0_152, VM 25.152-b16
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home/jre/bin/java
# VM options: <none>
# Warmup: 200 iterations, 1 s each
# Measurement: 200 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time

# Run complete. Total time: 17:49:25

Benchmark                                  (filling)   Mode   Cnt           Score         Error  Units
OptionalBenchmark.nullChecks                   empty  thrpt  2000   471803721.972 ±  116120.114  ops/s
OptionalBenchmark.nullChecks                   small  thrpt  2000   289181482.246 ± 3967502.916  ops/s
OptionalBenchmark.nullChecks                   large  thrpt  2000   260222478.406 ±  105074.121  ops/s
OptionalBenchmark.nullChecks                    full  thrpt  2000   282487728.710 ±   71214.637  ops/s
OptionalBenchmark.optionalsWithLambdas         empty  thrpt  2000   460931830.242 ±  335263.946  ops/s
OptionalBenchmark.optionalsWithLambdas         small  thrpt  2000    98688943.879 ±   20485.863  ops/s
OptionalBenchmark.optionalsWithLambdas         large  thrpt  2000    67262330.106 ±   50465.262  ops/s
OptionalBenchmark.optionalsWithLambdas          full  thrpt  2000   168070919.770 ±  352435.666  ops/s
OptionalBenchmark.optionalsWithMethodRefs      empty  thrpt  2000   460998599.579 ±   85063.337  ops/s
OptionalBenchmark.optionalsWithMethodRefs      small  thrpt  2000    98707338.408 ±   17231.648  ops/s
OptionalBenchmark.optionalsWithMethodRefs      large  thrpt  2000    68052673.021 ±   55285.427  ops/s
OptionalBenchmark.optionalsWithMethodRefs       full  thrpt  2000   169259067.479 ±  174402.212  ops/s

如您所见,我们的数据几乎相同。

【问题讨论】:

  • 我认为您没有充分预热 JVM,并且 200 计数太低了。见:How do I write a correct micro-benchmark in Java?full 可能更快,因为 JIT 终于启动了(请参阅规则 2 以检查是否是这种情况)。
  • 好帖子!您是否尝试过使用 -XX:CompileThreshold=10000000000000 之类的东西关闭 JIT?
  • 今晚(欧洲时间)我将尝试在禁用 JIT 的情况下再运行一次。我们拭目以待。
  • 你的基准看起来是正确的,不要听 cmets :) JMH 默认值是理智的。它已经关心热身。没有必要运行测试 so 太久。并且不要尝试 -XX:CompileThreshold - 在现代 JDK 中使用 does nothing

标签: java performance optional


【解决方案1】:

即使像 JMH 这样强大的工具也无法避免所有基准测试陷阱。 我发现这个基准有两个不同的问题。

1.

HotSpot JIT 编译器根据运行时配置文件推测性地优化代码。在给定的“完整”场景中,Optional 永远不会看到 null 值。这就是为什么Optional.ofNullable 方法(也被Optional.map 调用)恰好专门针对构造一个新的非空Optional 的非空路径进行了优化。在这种情况下,JIT 能够消除所有短期分配并在没有中间对象的情况下执行所有 map 操作。

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

在“小”和“大”场景中,映射序列最终以Optional.empty() 结束。也就是说,ofNullable 方法的两个分支都已编译,并且 JIT 不再能够消除中间 Optional 对象的分配 - 数据流图似乎过于复杂,Escape Analysis 无法成功。

通过使用-prof gc 运行 JMH 来检查它,您会看到“small”每次迭代分配 48 个字节(3 个 Optionals),“large”分配 96 个字节(6 个 Optionals),而“full”什么也不分配。

Benchmark                                                      (filling)  Mode  Cnt     Score     Error   Units
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      empty  avgt    5    ≈ 10⁻⁶              B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      small  avgt    5    48,000 ±   0,001    B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      large  avgt    5    96,000 ±   0,001    B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm       full  avgt    5    ≈ 10⁻⁵              B/op

如果将new Country("France") 替换为new Country(null),优化也会中断,并且“full”场景会比“small”和“large”慢。

或者,添加到setUp 的以下虚拟循环也将防止过度优化ofNullable,从而使基准测试结果更加真实。

    for (int i = 0; i < 1000; i++) {
        Optional.ofNullable(null);
    }

2.

令人惊讶的是,nullChecks 基准测试在“完整”情况下也出现得更快。这里的原因是类初始化障碍。请注意,只有“完整”案例会初始化所有相关类。在“小”和“大”情况下,nullChecks 方法指的是一些尚未初始化的类。这会阻止有效地编译nullChecks

如果您显式初始化 setUp 中的所有类,例如通过创建一个虚拟对象,那么nullChecks的“空”、“小”和“大”场景会变得更快。

Room dummy = new Room(new Flat(new Floor(new Building(new Block(new District(new City(new Country("France"))))))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2021-05-06
    • 2019-11-09
    • 2021-05-31
    • 2014-01-08
    • 2021-07-19
    • 2021-11-22
    相关资源
    最近更新 更多