10

Change slice::to_vec to not use extend_from_slice by JulianKnodt · Pull Request...

 3 years ago
source link: https://github.com/rust-lang/rust/pull/79186
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Contributor

JulianKnodt commented on Nov 19

edited by Mark-Simulacrum

I saw this Zulip thread, and didn't see any update from it, so I thought I'd try to fix it. This converts to_vec to no longer use extend_from_slice, but relies on knowing that the allocated capacity is the same size as the input.

Godbolt new v1
Godbolt new v2 w/ drop guard
Godbolt old version

After some amount of iteration, there are now two specializations for to_vec, one for Copy types that use memcpy, and one for clone types which is the original from this PR.

This is then used inside of impl<T: Clone> FromIterator<Iter::Slice<T>> for Vec<T> which is essentially equivalent to &[T] -> Vec<T>, instead of previous specialization of the extend function. This is because extend has to reason more about existing capacity by calling reserve on an existing vec, and thus produces worse asm.

Downsides: This allocates the exact capacity, so I think if many items are added to this Vec after, it might need to allocate whereas extending may not. I also noticed the number of faults went up in the benchmarks, but not sure where from exactly.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK