I was reading this Reddit comment which compares thin and fat pointers.
To be specific, the downsides of thin pointers within vectors:
User A heap allocates each object individually and takes many thin pointers to them. For user A thin pointers are pretty good, since the vtables are stored once, and the pointers are very lightweight. Now consider user B, which allocates the objects of the same type on vectors, and never views them polymorphically, or only occasionally does so. User B is paying for something that it does not use.
And the upside of fat pointers within vectors:
In Rust, one only pays this price when one actually goes ahead and creates a trait object. This is perfect for user B. For user A, this is far from perfect, since now its pointers are twice as big.
It does not make sense why fat pointers are better for User B because memory use seems to be the same or higher within vectors, not lower.
Fat pointer cost = 2 pointers + vtable size + data size
(VTABLE PTR -> VTABLE, DATA PTR -> DATA)
Thin pointer cost = 2 pointers + vtable size + data size
(PTR -> [VTABLE PTR -> VTABLE, DATA])
Given this layout, a vector of thin pointers will roughly take up capacity * 1 pointer in size and a vector of fat pointers will take capacity * 2 pointers in size. Overall required memory remains the same. What am I missing here, or is the author incorrect in his assessment?
You can have multiple references to the same object, either via immutably borrowing or via shared ownership like
Arc. For fat pointers, that means doubling the size of each reference. If you have lots of polymorphic references, fat pointers will use more space than thin pointers.However, fat pointers are only used if runtime polymorphism is needed - references to concrete types use thin pointers instead, since they know the type involved. Since Rust tends to use generics more than polymorphism, fat pointers aren't used very frequently. Conversely, thin pointers require adding a hidden vtable field to every structure that may be used polymorphically, which for most code would be a waste.