Dictionary vs switch in source generated code
I have doubt.
Im generating a compiled communication framework and the "endpoint handler" is a dictionary is int64 key-based with actions processing the context. keyvalue pairs are generated with my source generator. My question is. if I generate the equivalent switch to handle like 150 cases in compile time. would be inefficient?
40 Replies
benchmark it and see
my question would be more like for compile time and memory
Benchmark.bet reports memory as well
Not sure about build times
what about in terms of design?
That code will be hidden from the end user anyway
Seems like switch wins as I supposed
Was this a frozen dict or a normal one?
Iirc there was a dialog here that dict wins a switch in speed above some ~80 branches
normal, why?
same performance
Ok then, was worth checking
seems it has a slightly overhead cost
Something seems off about those tests. Would you mind sharing the test code?
done in LinqPad
I'll try providing random values
I wonder how a switch expression would fare
explain please
Explain... what exactly?
You benchmark dictionary vs switch statement
I wonder how performant would a switch expression be
And whether there would even be a difference
Switch expressions is a different way of writing switches, in case that's where the confusion comes from
Oh I understand, not switch statement. I dont like them that much (switch expressions)
You're the first person I meet who doesn't like switch expressions lol
I need to execute void methods
So?
I mean for this case
of course I use them, a lot
Switch expressions return the delegate which you can then execute
I know, but it introduces some overheads in the lowered version some times
this time I want to remove all possible overheads
is not that different from the dictionary approach, code-wise
Hence my suggestion to benchmark it
"some times" doesn't mean this time
still though it should be faster than dictionary, I mean switch expression
the variable
huh
that can be enhanced if expression returns a value, but for void, it's pretty much like this
almost the same if it returns an
int
You use an immutable dictionary here. These are actually significantly slower in lookup time compared to frozen dictionaries. Iirc correctly they are even slower than normal dictionaries.
I tried frozen, normal, immutable.. none of them were as fast as dictionary
You meant switch?
yep
If your keys are just 0, 1, 2, 3, why not array? Also, calling delegate will never be as fast as direct method call in switch
There's a difference of course. My test it's about which one reflect fastest lookup rather than measuring the final method to be called inside every case