itertools icon indicating copy to clipboard operation
itertools copied to clipboard

deref_cloned() ?

Open gilescope opened this issue 4 years ago • 5 comments

I wonder if we should have a deref_cloned() that did .map(|s| (*s).clone())? I see a few situations where people do cloned().cloned() to achieve the same effect (though I suspect that's not as efficient).

gilescope avatar Jan 24 '21 12:01 gilescope

I would expect that .cloned().cloned() is just as efficient -- maybe even more efficient since it's using core methods which could have some fancy internal optimizations.

scottmcm avatar Jan 24 '21 19:01 scottmcm

I was thinking it might make things clearer in the same vain that as_deref_mut and as_deref did when they were added to Option.

cloned().cloned() makes me wonder what's going on, where as deref_cloned() seems pretty explicit. Idk, maybe I should just get comfortable seeing cloned().cloned()...

Whether it should be in itertools or std I'm less sure, but I figured here wasn't a bad place to start.

gilescope avatar Jan 24 '21 20:01 gilescope

I would expect that .cloned().cloned() is just as efficient -- maybe even more efficient since it's using core methods which could have some fancy internal optimizations.

I wouldn't be so sure. Cloned doesn't implement SourceIter and InPlaceIterable, while Map does. I think this is probably a blunder but for the time being .cloned() is less efficient when collecting in place is possible. Godbolt example

SkiFire13 avatar Jan 27 '21 12:01 SkiFire13

Hmm, for some types they are equivilent. https://godbolt.org/z/K6xMfh, but I was thinking more about signaling intent.

gilescope avatar Jan 27 '21 14:01 gilescope

That's why I said "when collecting in place is possible". For that to be possible you need to have the original Vec's items type and the collecting items type to have the same size and alignment, which is not the case for &&i32 and i32. Here you can find the relevant logic.

SkiFire13 avatar Jan 27 '21 15:01 SkiFire13