More idiomatic to deref closure param or ref comparator

I have the following code:

"foo".chars().filter(|c| *c == 'o').collect::<String>()

Is it more idiomatic or less costly at runtime to instead do

"foo".chars().filter(|c| c == &'o').collect::<String>()

I typically do "foo".chars().filter(|&c| c == 'o').collect::<String>().

1 Like

It is as costly as the other example, because reference comparision will load the referenced value.

1 Like

I prefer the first version. Dereferencing a reference always feels a lot more "normal" than referencing a literal, and &'o' looks kinda weird.

In terms of performance, I'd assume both compile to roughly the same assembly. Although the first (which is pretty much identical to @matklad's solution) might be a tiny bit faster because the PartialEq impl for &char will need to dereference both arguments.

I don't think that difference will survive the optimizer.

2 Likes