Skip to content

perf: use Nullable<T>.GetValueOrDefault() instead of Nullable<T>.Value#21

Merged
neuecc merged 3 commits intoCysharp:mainfrom
nogic1008:perf/nullable
Dec 10, 2024
Merged

perf: use Nullable<T>.GetValueOrDefault() instead of Nullable<T>.Value#21
neuecc merged 3 commits intoCysharp:mainfrom
nogic1008:perf/nullable

Conversation

@nogic1008
Copy link
Copy Markdown
Contributor

Nullable<T>.Value always does null check as below.

If we know it's not null, we can avoid the extra if by using Nullable<T>.GetValueOrDefault() instead.

public struct Nullable<T> where T : struct
{
    private readonly bool hasValue;
    internal T value;

    public readonly T Value
    {
        get
        {
            if (!hasValue)
            {
                ThrowHelper.ThrowInvalidOperationException_InvalidOperation_NoValue();
            }
            return value;
        }
    }

    public readonly T GetValueOrDefault() => value;
}

Inspired by dotnet/coreclr#22297, .NET blog post

@neuecc
Copy link
Copy Markdown
Member

neuecc commented Dec 10, 2024

Thank you, I wasn't aware of that at all!
Thank you also for the blog reference, it's very helpful!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants