Re:Flags Are a Code Smell (2014)
by pylua on Saturday May 21, 2022 @09:09PM
(#31463902)
I feel like this is true, but just anecdotally. Is there any good literature on the cost of if/else vs polymorphism? Does branch prediction really work that well in practice vs polymorphism? I figure the approach in the article would potentially have bad cache locality, but I am unsure of how it would perform.
[ Parent
| on HN ]
Re:Flags Are a Code Smell (2014)
by jlajsdofwwfds on Sunday May 22, 2022 @01:32AM
(#31465146)
Isn't this essentially comparing switch/jmp table to a vtable?
The switch/jmp table can be optimized to be inline, vtable will likely incur a stack frame, plus usually 3 indirections.
When you have a closed set of types, then you know all cases for branching, in polymorphism you lose this power -- it's open ended.
This is another reason why languages should have exhaustive pattern matching with sum types.
Function pointers / vtables / polymorphism are slow, because they're indirect jumps (harder to predict). Function calls are slow, because there's work to do to save / restore state on the stack.
These don't matter much for big heavy functions, but tiny ones can seriously benefit from being inlined.
I have heard elsewhere that "game objects are just an index into a bunch of arrays for all the object properties" is fairly common practice, but well I don't write games myself.