using System.Diagnostics;
public static class Program
public static void Main()
int[] array = new int[150_000];
Array.Clear(array, 0, array.Length); FillIncremental_Vector(array, 1); Validate(array, 1);
Array.Clear(array, 0, array.Length); FillIncremental_Simple(array, 1); Validate(array, 1);
Array.Clear(array, 0, array.Length); array = Enumerable.Range(1, array.Length).ToArray(); Validate(array, 1);
Console.WriteLine($"Array.Length: {array.Length:#,0}, Loops: {loops:#,0}");
Measure("Simple", () => { for (int i = 0; i < loops; i++) { var temp = new int[array.Length]; FillIncremental_Simple(temp, i); } });
Measure("Vector", () => { for (int i = 0; i < loops; i++) { var temp = new int[array.Length]; FillIncremental_Vector(temp, i); } });
Measure("Range", () => { for (int i = 0; i < loops; i++) { var temp = Enumerable.Range(i, array.Length).ToArray(); } } );
static void Validate(int[] array, int start) { if (array.Select((n, i) => n - i - start).Any(n => n != 0)) throw new Exception("Validation failed!"); }
static void Measure(string title, Action action)
Console.WriteLine($"{title}");
Stopwatch stopwatch = new Stopwatch();
long mem0 = GC.GetTotalAllocatedBytes(true);
long mem1 = GC.GetTotalAllocatedBytes(true);
Console.WriteLine($"- Duration: {stopwatch.Elapsed.TotalMilliseconds:#,0} msec");
public static void FillIncremental_Simple(int[] array, int startValue)
ArgumentNullException.ThrowIfNull(array);
if (array.Length > 0 && startValue > (Int32.MaxValue - array.Length) + 1)
throw new ArgumentOutOfRangeException(nameof(startValue));
for (int i = 0, j = 0 + startValue; i < array.Length; i++, j++) array[i] = j;
public static void FillIncremental_Vector(int[] array, int startValue = 0)
ArgumentNullException.ThrowIfNull(array);
if (array.Length > 0 && startValue > (Int32.MaxValue - array.Length) + 1)
throw new ArgumentOutOfRangeException(nameof(startValue));
static void FillSimple(int[] array, int index, int length, int valueOffset)
int endIndex = index + length;
for (int i = index, j = index + valueOffset; i < endIndex; i++, j++)
if (!Vector.IsHardwareAccelerated || array.Length < Vector<int>.Count)
FillSimple(array, 0, array.Length, startValue);
FillSimple(array, 0, Vector<int>.Count, startValue);
Vector<int> vector = new(array);
Vector<int> step = new(Vector<int>.Count);
int endIndex = array.Length - Vector<int>.Count + 1;
for (i = Vector<int>.Count; i < endIndex; i += Vector<int>.Count)
FillSimple(array, i, array.Length - i, startValue);