Open
Description
As far as I know, Vec::splice() is the only way to extend the Vec from a slice in an arbitrary location. However, being a fairly universal api makes it slower than a hypothetical dedicated insert_from_slice
could be.
In fact, according to cargo bench
, for small vectors (let's say under 10) and number of elements to insert, it can be faster to insert them in a loop:
for i in 0..5 { data.insert(3, 77); }
than to call splice
:
let new = [77; 5];
data.splice(3..3, new.iter().copied());
splice
also seems to optimize badly in presence of constants. For example, looking at Godbolt, the optimizer can't seem to optimize
let tab = [77; 1];
vec.splice(5..6, tab.iter().cloned());
as good as
vec[5] = 77;
Or
let tab = [77; 1];
vec.splice(5..5, tab.iter().cloned());
as good as
vec.insert(5, 77);
It'd be nice if the function had lower overhead for small vectors/slices. Or maybe if another specialized method insert_from_slice(idx, slice)
was added that avoids all overhead for this particular use case.