Skip to content

BitOps: use the hardware Log2 on .NET #1303

Open

Description

What

BitOps.Log2(ulong) and BitOps.Log2(long) always smear the bits and index a De Bruijn table: six shift-or steps, a multiply, a shift and a table load. When the package compiles for .NET (Core 3.0 or later), System.Numerics.BitOperations.Log2 compiles to one lzcnt and an xor.

Evidence

DoxReloaded compiles these sources into a .NET 11 harness. Its board now finds the nearest button on a ray from the highest set bit of a 64-bit cell mask (BoardState.HighestSetBit). Under callgrind, BitOperations.Log2 inlined to or, lzcnt and xor, 3 instructions, where BitOps.Log2(long) runs about 14. That method calls BitOperations.Log2 under NET5_0_OR_GREATER and BitOps.Log2 otherwise.

Ask

Add a #if NETCOREAPP3_0_OR_GREATER branch to the Log2 overloads that calls System.Numerics.BitOperations.Log2, as #1285 did for PopCount and TrailingZeroCount. Keep the current code for Unity. BitOperations.Log2(0) returns 0, which matches the current contract.

Why

Then DoxReloaded can call BitOps.Log2 directly and delete its local branch.

From Ambiguous-Interactive/DoxReloaded#924.

DISCLOSURE: LLM-GENERATED TEXT

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions