Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
2
Indexable
Never
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

namespace sortedvsarray;

public class Program
{
    [Params(100, 1000, 10000)]
    public int N { get; set; }
    private int[] _arr;
    private List<int> _lst;
    private SortedSet<int> _set;

    [GlobalSetup]
    public void Setup(){
        _arr = new int[N];
        var rnd = new Random();
        for (int i = 0; i < N; i++) 
        {
            _arr[i] = rnd.Next();
        }
        _lst = InsertToArray();
        _set = InsertToSortedSet();
    }

    [Benchmark]
    public List<int> InsertToArray()
    {
        var lst = new List<int>();
        for (int i = 0; i < N; i++)
        {
            var pos = lst.BinarySearch(_arr[i]);
            if (pos < 0)
            {
                lst.Insert(~pos, _arr[i]);
            }
        }
        return lst;
    }

    [Benchmark]
    public SortedSet<int> InsertToSortedSet()
    {
        var set = new SortedSet<int>();
        for (int i = 0; i < N; i++)
        {
            set.Add(_arr[i]);
        }
        return set;
    }

    [Benchmark]
    public int TraversSet()
    {
        int i = 0;
        foreach (var o in _set)
        {
            i++;
        }
        return i;
    }

    [Benchmark]
    public int TraversArr()
    {
        int i = 0;
        foreach (var o in _lst)
        {
            i++;
        }
        return i;
    }
    public static void Main(string[] args)
    {
        BenchmarkRunner.Run<Program>();
        Console.WriteLine("Hello, World!");
    }
}