You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, the IL generated for operations on a bool? nb; like nb == true and nb is true is suboptimal. And since the runtime does not seem to understand the semantics of Nullable<T>, this results in suboptimal machine code being executed.
Namely:
The code nb == true generates branchless IL (see lifted comparison codegen can be improved #17261) equivalent to nb.GetValueOrDefault() == true & nb.HasValue, when it could be just nb.GetValueOrDefault().
The code nb is true generates branched IL equivalent to nb.HasValue ? nb.GetValueOrDefault() : false, when it could also be just nb.GetValueOrDefault().
The code nb is false generates branched IL equivalent to nb.HasValue ? !nb.GetValueOrDefault() : false when it could be the branchless !nb.GetValueOrDefault() & nb.HasValue.
The code nb ?? true generates branched IL equivalent to nb.HasValue ? nb.GetValueOrDefault() : true, when it could be the branchless nb.GetValueOrDefault() | !nb.HasValue.
Note that nb ?? false already produces the optimal code of nb.GetValueOrDefault().
Also note that the suggested code does not contain comparisons with true, which also result in unnecessary IL and machine code.
Currently, the IL generated for operations on a
bool? nb;likenb == trueandnb is trueis suboptimal. And since the runtime does not seem to understand the semantics ofNullable<T>, this results in suboptimal machine code being executed.Namely:
nb == truegenerates branchless IL (see lifted comparison codegen can be improved #17261) equivalent tonb.GetValueOrDefault() == true & nb.HasValue, when it could be justnb.GetValueOrDefault().nb is truegenerates branched IL equivalent tonb.HasValue ? nb.GetValueOrDefault() : false, when it could also be justnb.GetValueOrDefault().nb is falsegenerates branched IL equivalent tonb.HasValue ? !nb.GetValueOrDefault() : falsewhen it could be the branchless!nb.GetValueOrDefault() & nb.HasValue.nb ?? truegenerates branched IL equivalent tonb.HasValue ? nb.GetValueOrDefault() : true, when it could be the branchlessnb.GetValueOrDefault() | !nb.HasValue.Note that
nb ?? falsealready produces the optimal code ofnb.GetValueOrDefault().Also note that the suggested code does not contain comparisons with
true, which also result in unnecessary IL and machine code.SharpLab link.