|
|
|
|
|
by cgmorton
5077 days ago
|
|
It's an interesting point about the speed. In this case, since it's just a function pointer, there's no polymorphic overhead, so avoiding branches is a no-brainer. On the other hand, if you were actually extending a class to make a DoNothingClass version, then the overhead of dynamic binding plus the function call would make it somewhat slower (branch prediction on a NULL comparison will cost at most 5 clock cycles in a single-thread pipeline, or none if you predict right) on those checks where the DoNothingClass is the one you find. For instance, if you had a sparse array of Class* and wanted to iterate over them, the NULL check would probably be more efficient than pointers to a singleton NullClass, especially since branch prediction will start correctly predicting NULLs more often. So, you know, trade-offs. |
|
Being a little pedantic here: you can't safely say this part without knowing which kind of branch predictions the processor uses; and, more importantly, how deep the branch prediction can go. There are some processors that will branch predict once ... and then again, and again and again. The first one they get wrong, they have to roll back to that first one. But then, you're right. The more times that single method is called, depending on the implementation of branch prediction, the more often it's going to be right, and so as long as those values aren't changing often (I don't see why they would in the case we're trying to suggest), it may eventually fade into nothing.
Needs moar testing!