Skip to content

Benchmarks for #123434 (hez2010) #592

@EgorBot

Description

@EgorBot

Processing dotnet/runtime#123434 (comment) command:

Command

-amd -intel

using System.Runtime.CompilerServices;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkRunner.Run<ContainsTrue>();

public class ContainsTrue
{
    private string[] _found;

    private string[] _array;
    private List<string> _list;

    [Params(512)]
    public int Size;

    [GlobalSetup(Targets = new[] { nameof(Array) })]
    public void SetupArray()
    {
        _found = ArrayOfUniqueValues(Size);
        _array = _found.ToArray();
    }

    [Benchmark]
    public bool Array()
    {
        bool result = default;
        string[] collection = _array;
        string[] found = _found;
        for (int i = 0; i < found.Length; i++)
            result ^= collection.Contains(found[i]);
        return result;
    }

    [GlobalSetup(Targets = new[] { nameof(ICollection) })]
    public void SetupList()
    {
        _found = ArrayOfUniqueValues(Size);
        _list = new List<string>(_found);
    }

    [Benchmark]
    public bool ICollection() => Contains(_list);

    [MethodImpl(MethodImplOptions.NoInlining)]
    private bool Contains(ICollection<string> collection)
    {
        bool result = default;
        string[] found = _found;
        for (int i = 0; i < found.Length; i++)
            result ^= collection.Contains(found[i]);
        return result;
    }

    private static string[] ArrayOfUniqueValues(int count)
    {
        string[] result = new string[count];

        var random = new Random(42);

        var uniqueValues = new HashSet<string>();

        while (uniqueValues.Count != count)
        {
            string value = GenerateRandomString(random, 1, 50);

            if (!uniqueValues.Contains(value))
                uniqueValues.Add(value);
        }

        uniqueValues.CopyTo(result);

        return result;
    }

    private static string GenerateRandomString(Random random, int minLength, int maxLength)
    {
        var length = random.Next(minLength, maxLength);

        var builder = new StringBuilder(length);
        for (int i = 0; i < length; i++)
        {
            var rangeSelector = random.Next(0, 3);

            if (rangeSelector == 0)
                builder.Append((char)random.Next('a', 'z'));
            else if (rangeSelector == 1)
                builder.Append((char)random.Next('A', 'Z'));
            else
                builder.Append((char)random.Next('0', '9'));
        }

        return builder.ToString();
    }
}

(EgorBot will reply in this issue)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions