back

by uecker·4y ago·view on hn ↗
Generics can not reliably be optimized. They create specialized inline code by monomorphization (except partially in Go which is a bit smarter). Specialization and inlining can be good if it leads to simplificatons or bad when it leads to a combinatorial explosion, which is why optimizers are careful with it to avoid code bloat. Generics always create the bloat by default. If this were a good strategy, optimizers would always inline.

To reliable devirtualize function pointers in C you need to use non-standard extensions. But the best strategy is not let the optimizer decide and apply this very carefully inly for the few selected cases where it matters.

1 comments
> Generics can not reliably be optimized.

Choose to believe this, it's your loss. The fact is that performance sensitive domains like browsers/HFT/HPC/ML/etc are almost universally written in heavily templated C++. Just look at linear algebra libraries, C can't compete.

> They create specialized inline code by monomorphization

Neither generics nor monomorphization imply inlining, that's purely a performance optimization.

> (except partially in Go which is a bit smarter).

Are you joking? Go, already an extremely bloated language, somehow managed to implement generics with runtime overhead.

> Generics always create the bloat by default.

Generics only generate code you would have manually written/copied otherwise.

> But the best strategy is not let the optimizer decide and apply this very carefully inly for the few selected cases where it matters.

Two words, heterogeneous programming.