Skip to content

Improve Vec::truncate performance in no-opt builds #18097

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use core::ops;
use core::ptr;
use core::raw::Slice as RawSlice;
use core::uint;
use core::intrinsics::needs_drop;

use {Mutable, MutableSeq};
use slice::{MutableOrdSlice, MutableSliceAllocating, CloneableVector};
Expand Down Expand Up @@ -744,12 +745,17 @@ impl<T> Vec<T> {
#[unstable = "waiting on failure semantics"]
pub fn truncate(&mut self, len: uint) {
unsafe {
// drop any extra elements
while len < self.len {
// decrement len before the read(), so a failure on Drop doesn't
// re-drop the just-failed value.
self.len -= 1;
ptr::read(self.as_slice().unsafe_get(self.len));
// This improves performance at -O0
if needs_drop::<T>() {
// drop any extra elements
while len < self.len {
// decrement len before the read(), so a failure on Drop doesn't
// re-drop the just-failed value.
self.len -= 1;
ptr::read(self.as_slice().unsafe_get(self.len));
}
} else if len <= self.len {
self.set_len(len);
}
}
}
Expand Down Expand Up @@ -1645,10 +1651,8 @@ impl<T> Drop for Vec<T> {
// This is (and should always remain) a no-op if the fields are
// zeroed (when moving out, because of #[unsafe_no_drop_flag]).
if self.cap != 0 {
self.clear();
unsafe {
for x in self.as_mut_slice().iter() {
ptr::read(x);
}
dealloc(self.ptr, self.cap)
}
}
Expand Down