Help compilers optimize Object::cast_to()
#82903
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds an explicit null-check to
Object::cast_to()
. At-O2
both GCC and Clang seem to do the check themselves to avoid the call to the implementation ofdynamic_cast
when there's no object. However, MSVC (/O2
) doesn't add a check and will do the call regardless.All the three compilers can fuse the check here with any explicit check done at the call site. That said, if the contract of
cast_to()
is that it can take null just fine and any optimization is up to it (it's inlined anyway), the callers shouldn't be trying to outsmart it (or the compiler).One could argue that in cases where there's an object for sure, the check is superfluous. However, in compilers that don't add it before the call to
dynamic_cast
, it will have to happen within anyway.I've figured this out by using this little sample (with recent versions of the three compilers, targeting both x64 and ARM64):
https://godbolt.org/z/oPfdz8hTM