#rust enum pattern matching

11 messages · Page 1 of 1 (latest)

steel solar
#

how does rust handle pattern matching? I want to map some enum variants to other enum variants, and I'm currently just using a very large match statement. Is this going to be a performance issue (im doing this 4-5 times a second)? Is pattern matching linear or are there some shinengans going on so that its really efficient? Would using a hashmap or a phf map probably be faster than matching?

^ik its probably hard to know w/o benchmarking but i mean like in general

night dock
dense haven
#

there is no single rule about how a match is executed because it's up to the optimizer, which might generate a jump table or just compare them in sequence, or something else

#

from a codegen/optimization perspective, match is just a very-fancy if else if else ... and the optimizer tries to find a good implementation for both

#

if you care about this type of perf then it is a good habit to look at the (optimized!) assembly generated for your code and tweak the code to see what happens. and benchmark too.

crystal shale
#

As a rule of thumb, matches compile to one of the following

  • a noop. This tends to happen when turning integers to enum variants, and the underlying representation is identical
  • a jump table: the compiler generates an array of addresses, uses the scrutinee as an index, and jumps to the result
  • a decision tree: a pile of nested ifs, basically
  • a sequence of ifs: this one is extremely rare, but can happen.

As another rule of thumb, match compiles to the fastest possible code that could do the thing you asked

night dock
grim yoke
#

Generally, if it complies to a jump table (which is likely in your case if your variants don’t contain data, and probably even if they do), it will be constant time.

#

Also, speaking from experience, phf doesn’t support enum variants as keys.

dense haven
#

it can also be the case that worrying about a match is not a good plan because there are far bigger things to do about your program's performance

steel solar
#

Thanks for the help yall! 🙂