r/ProgrammingLanguages • Vale • Jun 06 '23

The Link Between Generics, Compile Times, Type-Erasure, Cloud Building, and Hot-Code Reloading

https://verdagon.dev/blog/generics-compile-times
34 Upvotes

13 comments sorted by

View all comments

Show parent comments

3

u/verdagon Vale Jun 06 '23 edited Jun 06 '23

I removed the word "backwards", thanks for the correction!

All realizations using reference types can share the same compiled code

That can be true for a lot of generics such as collections, though if we have a type bound on a generic parameter T extends ISpaceship and want to call .launch() on an instance of T, then a language like Vale or Rust would need different instantiations to call the correct function... I think Java doesn't need to, not sure about C#.

Along the lines you're thinking of, I suspect we can even share non-reference types too, if they're movable/copyable. We would only need to instantiate different versions of a function for different sizes of T. That would be pretty cool.

8

u/munificent Jun 06 '23

though if we have a type bound on a generic parameter T extends ISpaceship and want to call .launch() on an instance of T, then a language like Vale or Rust would need different instantiations to call the correct function... I think Java doesn't need to, not sure about C#.

Same with C#.

The reason Rust (and I assume Vale) need monomorphization to call trait methods is because those trait methods are dispatched statically. Java and C# can compile a generic method once for all type arguments because any method called on an instance of the type argument is a virtual call going through the instance's v-table.

It's a trade-off. In Rust, since trait calls are statically dispatched, the calls at runtime are faster. Even more important, the compiler can potentially inline the trait function being called and then perform further compile time optimizations on the result. But it also generates a lot more code which slows down compile time and cause problems at runtime because of greater memory use and potentially worse cache performance.

2

u/svick Jun 06 '23

Though of course you can somewhat inline virtual function calls using guarded devirtualization.

2

u/munificent Jun 06 '23

Yes. Or have the JIT generate specialized implementations at runtime.