dotnet / dotnet/runtime

JIT: Redundant range check

Open
#126,264 1 comment 0 reactions 1 assignee Claimed by @EgorBo View on GitHub
area-CodeGen-coreclr
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

https://godbolt.org/z/KMPGzdnv5

```csharp
public static string? TryUnwrapPrefix(string prefix, string path)
{
if (prefix == "/")
return path;

if (path == prefix)
return "/";

if ((uint)prefix.Length < (uint)path.Length)
if (path.StartsWith(prefix, StringComparison.Ordinal))
if (path[prefix.Length] == '/')
return new string(path.AsSpan(prefix.Length));

return null;
}
```

Compiled with an unnecessary range check.

If one of the initial `if` statements is removed or the `(uint)prefix.Length < (uint)path.Length` check is moved after `path.StartsWith` then the JIT correctly eliminates the redundant bounds check.

---

**This optimization works as expected in .NET 8-10**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.