Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I understand Rust does not hide representations enough for the compiler to be able to choose whether or not to monomorphize.

Any chance you could expand on that?



I don't know enough Rust to explain clearly or give examples :-) But like C++, Rust makes it explicit whether an object is boxed or not and the compiler doesn't get a choice about the memory layout, so it can't switch between monomorphization or uniform representation depending on the optimization level.


Yeah in Rust it's not up to the compiler whether generic code is monomorphized or dynamic dispatched, it's part of the language.

A monomorphized function looks like this:

    fn f1<T: Display>(v: &T) -> String {
        format!("{}", v)
    }
A dynamic dispatched function looks like:

    fn f2(v: &dyn Display) -> String {
        format!("{}", v)
    }
Note that we've added the dyn keyword, which tells rust to treat this as a trait object and use dynamic dispatch.

This is actually separate from boxing (these examples are just using normal unboxed references), although typically you would use trait objects with boxing as unboxed trait objects are awkward to work with.

See https://godbolt.org/z/PvM3ox for an example of the compilation: we get two versions of f1 specialized for u32 and u64, but just one for f2.


I'm so used to choosing between monomorphization and dynamic dispatch myself that I never thought of the possibility of a compiler being able to choose. Is the point to avoid monomorphization during dev to have faster compile times, and then enable monomorphization for release builds? That's a neat idea.

That makes me wonder what Java does these days. I haven't used Java much since about v1.6. Java took a different approach than C++ and Rust. I remember when generics were introduced, they were basically syntactic sugar for type casts (for backwards compatibility). That implies that Java at the time didn't monomorphize generics. I think the language has evolved a lot since those days, so I wonder if it does any monomorphization today.


Java is slightly more complicated. It can make assumptions about the code (even if it can't prove they always hold!) and specialize some things but not others.

Generally, the jit can specialize the code making assumptions about the real type under interfaces/polymorphism, which types the generic parameters will be, or even which target virtual dispatch will always hit.

But for the objects themselves, it never specializes layout in any way (short of removing an allocation entirely).

... I think. I'm no expert in this, ask chrisseaton.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: