5 ms·
Swift uses reference counting for reference types, but emphasizes value types. Rust supports reference counting for certain types, but emphasizes value types to
by millstone 10y ago
Swift uses reference counting for reference types, but emphasizes value types. Rust supports reference counting for certain types, but emphasizes value types too.
Also observe that Rust's drop flag is a form of (1-bit) reference counting.
In this particular area, they are more similar than different.
- Veedrac 10y agoRust's drop flag is quite different because it's local. Most pointers are not reference counted in Rust, whereas they are in Swift. Similar perhaps, but not that similar.
- millstone 10y agoWhich pointers? Here's all the different pointers I know of in Rust, and their equivalents in Swift: Rc/Arc <-> class types Raw pointers <-> UnsafePointer/UnsafeMutablePointer References <-> inouts Trait objects <-> Protocol objects Box <-> indirect enum (arguably) Did I miss any? Of the core language features, protocol objects are the only case where Swift uses reference counting and Rust does not.
- pcwalton 10y agoSwift doesn't have the borrow checker, which means that in order to ensure safety the expressiveness is really limited unless you use RC. That's why essentially all Swift code uses RC, and Rust code rarely does. There's a big difference between technically having manual memory management and having it actually widely used and practical.
- millstone 10y agoYes, RC is the primary way to safely manage lifetimes of reference types in Swift. You can drop down to unsafe constructs to avoid RC overhead, and I sometimes do that in hot loops. Using unsafe to improve performance is not unfamiliar in Rust either, though Rust gives you better tools for building safe abstractions around it. Shared ownership is routine in UI programming - think event handlers, etc. These are the apps most commonly written in Swift. Does Rust avoid needing shared ownership for these types of apps? If so, how?
- pcwalton 10y agoRust's drop flag is totally unlike Swift's atomic heap reference counting. The drop flag is just an implementation detail that procedures sometimes use to determine whether to run the destructor. It is usually optimized away. It is quite feasible to program without drop flags if you really don't want them, though they never show up in profiles (unlike swift_retain). We could statically eliminate drop flags if we wanted to, via tail duplication. (But we don't, because the drop flags have effectively zero runtime overhead, unlike RC.)