tree-ware / tree-ware-kotlin-core

Apache License 2.0
1 stars 0 forks source link

Dispatch by checking an enum value rather than checking the class #14

Closed deepak-nulu closed 3 years ago

deepak-nulu commented 3 years ago

The dispatch methods currently check class types using the following when expression:

when (leader) {
    is Model<LeaderAux> -> {
        visitor.visit(leader)
    }
    is RootModel<LeaderAux> -> {
        visitor.visit(leader)
    }
    is EntityModel<LeaderAux> -> {
        visitor.visit(leader)
    }
    is PrimitiveFieldModel<LeaderAux> -> {
        visitor.visit(leader)
    }
   ...
}

This translates to if checks in byte code; the decompiled code looks like the following:

      Object var10000;
      if (leader instanceof Model) {
         var10000 = visitor.visit((Model)leader);
      } else if (leader instanceof RootModel) {
         var10000 = visitor.visit((RootModel)leader);
      } else if (leader instanceof EntityModel) {
         var10000 = visitor.visit((EntityModel)leader);
      } else if (leader instanceof PrimitiveFieldModel) {
         var10000 = visitor.visit((PrimitiveFieldModel)leader);
      } ...

A lot of checks need to be performed if the class type is the last one being checked. Benchmarking shows the difference in throughput between dispatching model elements that match the first and last checks:

benchmarks summary:
Benchmark                                                         Mode  Cnt           Score   Error  Units
treeWare.model.operator.DispatchBenchmarks.dispatchByClassFirst  thrpt    2   453415706.530          ops/s
treeWare.model.operator.DispatchBenchmarks.dispatchByClassLast   thrpt    2     5226479.126          ops/s

Throughput should be better and consistent if dispatching was performed by switching on enum values that indicate the type of the model elements.

deepak-nulu commented 3 years ago

The following benchmarks show that dispatching by enum is faster (higher throughput) than dispatching by class, and also more consistent between model elements that match the first and last checks:

benchmarks summary:
Benchmark                                                         Mode  Cnt          Score   Error  Units
treeWare.model.operator.DispatchBenchmarks.dispatchByClassFirst  thrpt    2  467129735.883          ops/s
treeWare.model.operator.DispatchBenchmarks.dispatchByClassLast   thrpt    2    5299428.140          ops/s
treeWare.model.operator.DispatchBenchmarks.dispatchByEnumFirst   thrpt    2  706648973.610          ops/s
treeWare.model.operator.DispatchBenchmarks.dispatchByEnumLast    thrpt    2  710008175.641          ops/s