On Fri, Nov 8, 2013 at 6:24 AM, Niko Matsakis <n...@alum.mit.edu> wrote:

> On Thu, Nov 07, 2013 at 04:48:06PM -0500, Daniel Micay wrote:
> > Owned boxes shouldn't be commonly used. There's close to no reason to use
> > one for anything but a recursive data structure or in rare cases for an
> > owned trait object.
>
> I don't really agree with this statement. I agree that those are the
> two cases an owned pointer is mandatory, and that the choice between
> `T` and `~T` is a matter of optimization, and hence something that
> should be measured.
>
> However, I don't think it's *so* unusual that one might want
> pointer-sized values. Off the top of my head, here are some more
> scenarios where owned pointers certainly make sense:
>
> 1. Options, particularly those that are frequently none.
>    `Option<~HashMap<...>>` is a single word in size. If it is
>    `None`, that's just a NULL pointer.
>
> 2. Enum variants. The size of an enum is the size of its largest
>    variant. If you have:
>
>        enum Foo {
>            Opt1(uint),
>            Opt2(HashMap<...>),
>            Opt3(uint, uint, uint),
>        }
>
>    You are potentially wasting a lot of space, unless `Opt1` is very
>    rare. You'd be better off doing something like:
>
>        enum Foo {
>            Opt1(uint),
>            Opt2(~HashMap<...>),
>            Opt3(~Opt3)
>        }
>
>        struct Opt3 { uint, uint, uint }
>
>
>
>
> Niko
>

I don't think the need to do micro-optimizations like this is *common*
though. It gets to the point where you're optimizing for the
characteristics of a specific allocator because they use different size
class buckets so trusting a profiler on one platform isn't enough.

There's a very real cost to the indirection, extra pointers in the CPU
cache, and all the landing pad stuff that ends up generated. I don't deny
that indirection can be useful for optimization, but it's unintuitive and
often not a portable improvement.

In the Boxes section I wrote for the tutorial, it includes this:

> In uncommon cases, the indirection can provide a performance gain or
memory reduction by making values smaller. However, unboxed values should
almost always be preferred.
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to