dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.09k stars 1.56k forks source link

evaluate optimization for instanceof-interface #29097

Open sigmundch opened 7 years ago

sigmundch commented 7 years ago

It might be possible to optimize ischecks if we know that the target is an interface and that all implementations of that interface are also derived from a common base class that implements such interface. For example in this code:

class I {}
class A implements I {}
class B extends A {}
class C extends B implements I {}

...
[new A(), new B(), new C()].forEach((x) => print(x is I));

We should be able to compile x is Ias x is A. That would allow us to tree-shake the interface entirely and possibly make the check more efficient.

/cc @rakudrama

rakudrama commented 7 years ago

In the above example we tell from the type hierarchy that testing an interface type is equivalent to testing an extended-only type. We can change all x is I to x is A and remove I from the program. The optimization works regardless of what is in the list.

I'd rather implement type test strength reduction on a per-check basis. The type hierarchy might not support the cheaper test, but we might know enough about x to know that a cheaper tests can be used. If all tests reduce to a cheaper test then we have optimized out the demand for is I.

Is there something similar to be done with as I and type assertions? These produce errors containing the type name so a similar strength reduction would change the error message.