Hacker News new | ask | show | jobs
by brundolf 1422 days ago
To be honest, this seems like a bizarre choice. Rc<> would not only be more idiomatic, it seems like it would even be more ergonomic because you don't then have to worry about passing your whole Vec around everywhere you want to access one of its elements

Doing it with an indexed Vec is basically re-inventing your own memory management system on top of the native one, which as you point out can get very contrived and error-prone. Because then you also have to re-invent allocation/freeing, removal of holes, etc etc.

People sometimes do this in VMs/interpreters where they really do need custom/"unsafe"[1] memory management, which makes sense, but it's definitely not needed for application code like this

[1] Of course it's still memory-safe, but it's more fallible in terms of panics and bugs, as you've pointed out

1 comments

Saying it's "idiomatic" isn't very actionable advice for people, the average programmer hears that and doesn't really know when to use Rc over other approaches. I also wouldn't say to always go with the most ergonomic approach, that approach can lead to code that is even slower than other languages.

I would rather advise: don't reuse indices, even if that is the simplest solution that complies with the borrow checker. When one finds themselves reusing like that, that's when to turn to other more expensive approaches such as Rc.

I don't think the average programmer would think to do the Vec indexing for this situation in the first place

> that's when to turn to other more expensive approaches such as Rc

If you're saying this was done just as an optimization... all I can say is, I hope you benchmarked first. As estebank pointed out, Rc is very fast: https://news.ycombinator.com/item?id=32240478. It can even be faster than mark-and-sweep in some situations. In fact the Swift language only uses reference-counting, not mark-and-sweep, at the language level.

If you profiled and found that the Vec approach solved some performance problem you had with reference-counting, then so be it. But I would be surprised if it meaningfully helped, and shocked if it helped enough to outweigh the extra complexity.