Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use obj is Array instead of obj.GetType().IsArray #4656

Merged
merged 1 commit into from
Mar 9, 2024

Conversation

RenderMichael
Copy link
Contributor

This change has a tiny (but consistent) performance boost, and more importantly improves readability.

This should function exactly the same. Type.IsArray differs only in edge cases which can never be hit by a Type returned by GetType() (the Array type, interfaces, etc).

Benchmark code
using BenchmarkDotNet.Attributes;

namespace NUnit.Framework;

#pragma warning disable SA1010 // Opening square brackets should be spaced correctly

[MemoryDiagnoser(false)]
public class ArrayEqualsBenchmarks
{
    [Benchmark]
    public void AssertStringsEqual()
    {
        string[] actual = ["one", "two", "three"];
        string[] expected = ["one", "two", "three"];
        Assert.That(actual, Is.EqualTo(expected));
    }

    [Benchmark]
    public void AssertStringsEqualFalse()
    {
        string[] actual = ["one", "two", "three"];
        string[] expected = ["one", "two", "four"];
        Assert.That(actual, Is.Not.EqualTo(expected));
    }

    [Benchmark]
    public void AssertIntsEqual()
    {
        int[] actual = [1, 2, 3];
        int[] expected = [1, 2, 3];
        Assert.That(actual, Is.EqualTo(expected));
    }

    [Benchmark]
    public void AssertIntsEqualFalse()
    {
        int[] actual = [1, 2, 3];
        int[] expected = [1, 2, 4];
        Assert.That(actual, Is.Not.EqualTo(expected));
    }
}

Before:

Method Mean Error StdDev Allocated
AssertStringsEqual 300.4 ns 4.64 ns 4.34 ns 728 B
AssertStringsEqualFalse 604.3 ns 11.58 ns 10.83 ns 1488 B
AssertIntsEqual 930.9 ns 12.96 ns 10.82 ns 1024 B
AssertIntsEqualFalse 1,214.0 ns 9.94 ns 8.30 ns 1776 B

After:

Method Mean Error StdDev Allocated
AssertStringsEqual 294.7 ns 3.86 ns 3.61 ns 728 B
AssertStringsEqualFalse 595.9 ns 6.70 ns 5.94 ns 1488 B
AssertIntsEqual 915.7 ns 13.69 ns 12.81 ns 1024 B
AssertIntsEqualFalse 1,193.5 ns 8.26 ns 6.90 ns 1776 B

Copy link
Member

@manfred-brands manfred-brands left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice and clean.

@manfred-brands manfred-brands merged commit f4f266b into nunit:master Mar 9, 2024
5 checks passed
@RenderMichael RenderMichael deleted the arrays branch March 9, 2024 07:27
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.

None yet

2 participants