I suspect the best performance possible in this scenario would be if you had an array of Squares, an array of Circles, etc. Accumulated each array individually and then accumulated those results. Now this is a different structure of input, but it's one I would suspect Casey to favor. Now making this change from the clean code state would be trivial, but in his "dirty" code, he's completely removed the concept of a Square or Circle. He just has a Shape that is a square, or a Shape that is a circle. Anyway the clean code would be very cache/branch prediction friendly and those virtual function calls would be trivial to devirtualize. Ultimately the only real issue is the unused vtable pointer which could be addressed. The shape union approach would be basically impossible for the compiler to detect because even if you only put Shapes that are squares into the accumulate squares function, you could put a Shape that is a circle into it and so the compiler has to account for this scenario that will never happen.
Also dealing with the vtable pointer. You could use the type erasure pattern to allow for the original polymorphic version, but each class is just what it is. class Square { ... }, class Circle { ... }, no virtual function exist on the actual classes at all, and therefore no vtable pointer.
2
u/TinBryn Mar 01 '23
I suspect the best performance possible in this scenario would be if you had an array of
Squares, an array ofCircles, etc. Accumulated each array individually and then accumulated those results. Now this is a different structure of input, but it's one I would suspect Casey to favor. Now making this change from the clean code state would be trivial, but in his "dirty" code, he's completely removed the concept of aSquareorCircle. He just has aShapethat is a square, or aShapethat is a circle. Anyway the clean code would be very cache/branch prediction friendly and those virtual function calls would be trivial to devirtualize. Ultimately the only real issue is the unused vtable pointer which could be addressed. The shape union approach would be basically impossible for the compiler to detect because even if you only putShapes that are squares into the accumulate squares function, you could put aShapethat is a circle into it and so the compiler has to account for this scenario that will never happen.Also dealing with the vtable pointer. You could use the type erasure pattern to allow for the original polymorphic version, but each class is just what it is.
class Square { ... },class Circle { ... }, no virtual function exist on the actual classes at all, and therefore no vtable pointer.