What's the most efficient way to reuse an iterator in Rust?

前端 未结 3 408
花落未央
花落未央 2020-12-20 13:55

I\'d like to reuse an iterator I made, so as to avoid paying to recreate it from scratch. But iterators don\'t seem to be cloneable and collect mov

3条回答
  •  佛祖请我去吃肉
    2020-12-20 14:27

    You should profile before you optimize something, otherwise you might end making things both slower and more complex than they need to.

    The iterators in your example

    let my_iter = my_string.unwrap_or("A").chars().flat_map(|c|c.to_uppercase()).map(|c| Tag::from(c).unwrap() );
    

    are thin structures allocated on the stack. Cloning them isn't going to be much cheaper than building them from scratch.

    Constructing an iterator with .chars().flat_map(|c| c.to_uppercase()) takes only a single nanosecond when I benchmark it.

    According to the same benchmark, wrapping iterator creation in a closure takes more time than simply building the iterator in-place.

    Cloning a Vec iterator is not much faster than building it in-place, both are practically instant.

    test construction_only    ... bench:           1 ns/iter (+/- 0)
    test inplace_construction ... bench:         249 ns/iter (+/- 20)
    test closure              ... bench:         282 ns/iter (+/- 18)
    test vec_inplace_iter     ... bench:           0 ns/iter (+/- 0)
    test vec_clone_iter       ... bench:           0 ns/iter (+/- 0)
    

提交回复
热议问题