Hacker News new | ask | show | jobs
by mikeash 3193 days ago
You're right, String has three fields. It's Array that's just a single reference. Is the overhead of passing three fields as a parameter so high that passing a reference is faster? Pointer chasing isn't free either, after all. I can certainly imagine scenarios where that sort of microoptimization pays off, but it seems like it would be rare.

As far as large structures go, I'm thinking "large" like hundreds of fields. Any time I've seen people concerned about large structures, they misunderstand the value-typedness of things like String and Array and are worried about the contents of those things, which isn't really part of the size of the struct itself. But that's just what I've seen.

1 comments

From the documentation of Array for Swift it has the same behaviour as Rust's Vec (it's growable, it allocates double the capacity after reaching max length). I'd find it pretty odd if it didn't share the same 3 word length as String. Also, how would it quickly know it's length if it didn't also store it's length in the same structure as the ptr to it's heap location? You'd have to chase 2 pointers just to get the length.

I'd guess that Swift also has something analogous to an array slice, which would be a (possibly) immutable borrow to a chunk of array data on the heap. This also happens to be a good use case for borrows.

From the other comment here it seems like Swift is pursuing an ownership model similar to Rusts, in which case, immutable borrows will become more important when you think about struct contents. You can only have a single owner, but you can specify many borrowers. This kind of thing is important when you have an array or vector of types, often you don't want those types to have a single owner but you want them to be populated or store a reference from somewhere else.

Anyway, don't dismiss the concept out of hand. Immutable borrows definitely have their uses, whether it's made explicit to you or not in Swift is another thing entirely.

The array capacity and length are stored inline before the contents. So you chase one pointer to get the capacity, length, or something stored in the array.

Swift does have ArraySlice, but I don't get how borrows factor into that. Seems vaguely similar in concept, except ArraySlice exists to represent a subset of the original array, not just so you can pass arrays by reference. Since arrays are already passed by reference under the hood, that wouldn't really be useful.

I'm not dismissing the concept out of hand, so I'm not sure why you're warning me about that....