Avoid boxing in flag enum checks by using bitwise tests#705
Merged
Conversation
Enum.HasFlag boxes both the enum value and the flag argument on every call. The configuration option getters are queried heavily during generation, so this shows up as ~14.7 MB (~5%) of allocations on the terrafx d3d12 generation under Tier0/JIT. Replace HasFlag with a direct bitwise test. All of the affected flags are single-bit, so (value & flag) != 0 is exactly equivalent. The JIT elides HasFlag boxing via an intrinsic once the getters tier up, and NativeAOT is optimized throughout, so this is a no-op there and a win for local/JIT-hosted runs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Replace Enum.HasFlag with direct bitwise tests. HasFlag boxes both the enum value and the flag argument on every call. The configuration option getters are queried heavily during generation, so this shows up as ~14.7 MB (~5%) of allocations when profiling a real-world workload (the terrafx/terrafx.interop.windows d3d12 generation) under Tier0/JIT.
All of the affected flags are single-bit, so (value & flag) != 0 is exactly equivalent to HasFlag, and !x.HasFlag(f) becomes (x & f) == 0.
The JIT elides HasFlag boxing via an intrinsic once the getters tier up, and NativeAOT is optimized throughout -- so this is effectively a no-op for the shipped
ClangSharpPInvokeGeneratortool and a win for local/JIT-hosted runs (tests, in-process generation, short-lived processes that never fully tier up).Sites: the configuration option getters in
PInvokeGeneratorConfiguration(the hot path), plusValueDesc,PInvokeGenerator.VisitDecl, and the CLIProgram.Behavior-preserving; all 3706 tests pass with a 0-warning build.