Skip to content

Redundant length check when using Span<byte> => new byte[] #12571

Closed
@benaadams

Description

@benaadams
public static bool IsHexadecimalChar(char c)
{
    var charToHex = CharToHexLookup;
    var i = (int)c;
    return (uint)i < (uint)charToHex.Length && charToHex[i] != 0xff;
}

private static ReadOnlySpan<byte> CharToHexLookup => new byte[]
{
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 15
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 31
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 47
    0x0,  0x1,  0x2,  0x3,  0x4,  0x5,  0x6,  0x7,  0x8,  0x9,  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 63
    0xFF, 0xA,  0xB,  0xC,  0xD,  0xE,  0xF,  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 79
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 95
    0xFF, 0xa,  0xb,  0xc,  0xd,  0xe,  0xf // 102
};

Generates

PathStringHelper.IsHexadecimalChar(Char)
    L0000: sub rsp, 0x48
    L0004: movzx eax, cx
    L0007: cmp eax, 0x67
    L000a: jae L002f
    L000c: cmp eax, 0x67   ; this check is same as above
    L000f: jae L0036           
    L0011: movsxd rax, eax
    L0014: mov rdx, 0x1a744990bc8
    L001e: add rax, rdx
    L0021: cmp byte [rax], 0xff
    L0024: setnz al
    L0027: movzx eax, al
    L002a: add rsp, 0x48
    L002e: ret
    L002f: xor eax, eax
    L0031: add rsp, 0x48
    L0035: ret
    L0036: call System.ThrowHelper.ThrowIndexOutOfRangeException()
    L003b: int3

category:cq
theme:basic-cq
skill-level:intermediate
cost:medium

Metadata

Metadata

Assignees

Labels

JitUntriagedCLR JIT issues needing additional triagearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIoptimization

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions