Repository: dotnet/runtime
File: src/libraries/System.Private.CoreLib/src/System/Collections/BitArray.cs (C#)

Code before:

            if (extraBits == 0)
            {
                return false;
            }

            byte mask = (byte)((1 << (int)extraBits) - 1);
            return (_array[byteCount] & mask) != 0;
        }

        /// <summary>Computes the number of bits that are set in the <see cref="BitArray"/>.</summary>
        /// <returns>The number of set bits in the <see cref="BitArray"/>.</returns>
        public int PopCount()
        {
            int count = 0;
            foreach (byte b in _array)
                count += byte.PopCount(b);
            return count;
        }

        /// <summary>Computes the number of trailing zero bits in the <see cref="BitArray"/>.</summary>
        /// <returns>The number of trailing zero bits in the <see cref="BitArray"/>.</returns>
        public int TrailingZeroCount()
        {
            int count = 0;
            for (int i = 0; i < _array.Length; i++)
            {
                if (_array[i] != 0)
                    return byte.TrailingZeroCount(_array[i]) + count;

                count += BitsPerByte;
            }

            return _bitLength;
        }

        /// <summary>Computes the number of leading zero bits in the <see cref="BitArray"/>.</summary>
        /// <returns>The number of leading zero bits in the <see cref="BitArray"/>.</returns>
        public int LeadingZeroCount()
        {
            int count = _bitLength - _array.Length * BitsPerByte; // offset for extra bits beyond _bitLength
            for (int i = _array.Length - 1; i >= 0; i--)
            {
                if (_array[i] != 0)
                    return byte.LeadingZeroCount(_array[i]) + count;

                count += BitsPerByte;
            }

            return _bitLength;
        }

Review comment (suggestion):
According to comment for `_array`, there might be extra bytes (e.g. BitArray of 2 bits can have `_array.Length==4`). `GetByteArrayLengthFromBitLength` is used in other methods in the class.

Perhaps it would be possible to use `IndexOfAnyExcept((byte)0)` to leverage some vectorization when possible.

Code after:
            RoundUpToMultipleSizeOfInt32(GetByteArrayLengthFromBitLength(bitLength));

        /// <summary>Allocates a new byte array of the specified bit length, rounded up to the nearest multiple of sizeof(int).</summary>
        private static byte[] AllocateByteArray(int bitLength)
        {
            int byteLength = GetAlignedByteArrayLength(bitLength);
            Debug.Assert(byteLength >= 0, "byteLength should be non-negative.");
            Debug.Assert(byteLength % sizeof(int) == 0, "byteLength should be a multiple of sizeof(int).");
            return bitLength != 0 ? new byte[byteLength] : [];
        }

        /// <summary>Nop on little endian, reverses the endianness of <paramref name="value"/> on big endian.</summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static int ReverseIfBE(int value) =>
            BitConverter.IsLittleEndian ? value : BinaryPrimitives.ReverseEndianness(value);

        private static void ThrowArgumentOutOfRangeException(int index) =>
            throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_IndexMustBeLess);

        private sealed class BitArrayEnumeratorSimple : IEnumerator, ICloneable
        {
            private static readonly object s_boxedTrue = true;
            private static readonly object s_boxedFalse = false;

            private readonly BitArray _bitArray;
            private readonly int _version;
            private int _index;
            private object _currentElement = s_boxedFalse;

            internal BitArrayEnumeratorSimple(BitArray bitArray)
            {
                _bitArray = bitArray;
                _index = -1;
                _version = bitArray._version;
            }

            public object Clone() => MemberwiseClone();

            public bool MoveNext()
            {
                if (_version != _bitArray._version)
                {
                    throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
                }

                if (_index < (_bitArray._bitLength - 1))
                {
                    _index++;
                    _currentElement = _bitArray.Get(_index) ? s_boxedTrue : s_boxedFalse;
                    return true;
                }