4 ms·
This code from BinaryHeap doesn't need unsafe, but it gladly uses it for performance. The comment in the code explains it. http://doc.rust-lang.org/src/collect
by kzrdude 12y ago
This code from BinaryHeap doesn't need unsafe, but it gladly uses it for performance. The comment in the code explains it.
http://doc.rust-lang.org/src/collections/binary_heap.rs.html#501-544 http://doc.rust-lang.org/src/collections/binary_heap.rs.html...
- steveklabnik 12y ago"Gladly" isn't quite accurate: https://github.com/rust-lang/rust/pull/4146#issuecomment-11408758 https://github.com/rust-lang/rust/pull/4146#issuecomment-114... This is exactly how I'd expect to see `unsafe` used: as an additional optimization in situations where you can't get better in any other way, and with a big-'ol comment explaining exactly why. Well, one of the ways, at least.
- Animats 12y agoThat's exactly how unsafe ought NOT to be used. All they saved here were about two machine instructions per operation. On some superscalar CPUs, those might be overlapped anyway. "Swap" is a safe operation in a single-ownership world, and Rust used to have a swap operator. That was taken out, because it could be done with a template. The penalty is that the compiler doesn't know you're doing a swap. Swap has some potential optimizations. I am very suspicious of unsafe code for claimed "performance" reasons. That leads to exploits and backdoors.
- steveklabnik 12y agoI agree that 'unsafe for performance' should be something of a last resort, but do not have the knowledge to comment on this specific situation.
- dbaupp 12y agoWhere did you get the two machine instructions number? A swap could easily be a exchange of e.g. 16 (the size of a slices &[T]/&str on a 64-bit computer) or 24 bytes (Vec<...>/String) (or larger), and there's no way to use single SIMD instructions for these in general. Also, "per operation" is vague, since the swaps would have to happen repeatedly in a loop, so a single .insert call is likely to result in multiple swaps.
- kzrdude 12y agook, I accept. I know that it couldn't have been that easy to accept, given that it relies on the specifics of zero on drop etc. No better coder than strcat to do it though.