Multiple filter or just one

Hi!
I'm wondering what is the best way to apply multiple filters to a large vector of objects. For example:

struct Pokemon {
  id: i32,
  name: String,
  type: (String, String),
}

let pokedex: Vec<Pokemon> = <the_all_pokedex>

// First way

pokedex
  .iter()
  .filter(filter1)
  .filter(filter2)
  .filter(filter3)
  .filter(filter4)
  .filter(filter5)
  .collect::<Vec<Pokemon>>()

// Second way

pokedex
  .iter()
  .filter(|pokemon|
    filter1(pokemon) &&
    filter2(pokemon) &&
    filter3(pokemon) &&
    filter4(pokemon) &&
    filter5(pokemon)
  )
  .collect::<Vec<Pokemon>>();

I think it probably doesn't matter.

The order will matter more than which style you use: Everything is tested with filter1, but only the items that pass get tested against filter2 and so on in either case. So, put the filter that will probably be most restrictive (throw out the most items) first.

if the filters are function pointers, it doesn't matter. if they're not, you should see increased performance in debug mode with the inlined version.

2 Likes

Alright!
Thanks @alice, @2e71828, and @Phlopsi for your answers!