Skip to content

Add extend_from_array#79892

Closed
scottmcm wants to merge 4 commits intorust-lang:masterfrom
scottmcm:extend-array
Closed

Add extend_from_array#79892
scottmcm wants to merge 4 commits intorust-lang:masterfrom
scottmcm:extend-array

Conversation

@scottmcm
Copy link
Member

This PR inspired by noticing that the following, while it seems reasonable, actually contains 4 calls to reserve in the ASM:

pub fn push3_demo(v: &mut Vec<i32>, a: i32, b: i32, c: i32) {
    v.reserve(3);
    v.push(a);
    v.push(b);
    v.push(c);
}

https://rust.godbolt.org/z/EWExYP

Like there's extend_from_slice for cloning, it seems like it would be logical to have an extend_from_array to encapsulate the obvious unsafe code for moving the elements to the end of the vector. And, indeed, that turns out to generate tighter assembly than any of the other options I tried, including array::IntoIter and chains-of-onces: https://rust.godbolt.org/z/Wq7qah

I ended up putting this on Extend, as it makes particular sense on anything that can take advantage of the memory continuity of the array -- this PR implements it for Vec and VecDeque -- but would also be handy as a way to tersely add a known number of elements to any collection by move. It has the nice default implementation in terms of the array IntoIter, so that things without special overrides for it can still do something reasonable, as that provides an exact size_hint.

But touching a trait means it should probably get some libs eyes on it even to go in unstable, so let's try
r? @m-ou-se

(A different approach for this could be something like push_chunk, in the sense of as_chunks.)

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

I-slow Issue: Problems and improvements with respect to performance of generated code. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants