The following code reads space-delimited records from stdin, and writes comma-delimited records to stdout. Even with optimized builds it\'s rather slow (about twice as slow
The safe solution is to use .drain(..) instead of .clear()
where ..
is a "full range". It returns an iterator, so drained elements can be processed in a loop. It is also available for other collections (String
, HashMap
, etc.)
fn main() {
let mut cache = Vec::<&str>::new();
for line in ["first line allocates for", "second"].iter() {
println!("Size and capacity: {}/{}", cache.len(), cache.capacity());
cache.extend(line.split(' '));
println!(" {}", cache.join(","));
cache.drain(..);
}
}