C# Array.Fill 值类型优化。

当我们对一块值类型数组操作,重置和填充数据时,最好用Array.Fill 方法,对于引用类型,没有变化。 对于值类型,是直接操作内存,会更快一点。
微软源码如下 https://github.com/dotnet/runtime/blob/1d1bf92fcf43aa6981804dc53c5174445069c9e4/src/libraries/System.Private.CoreLib/src/System/Array.cs#L1107C13-L1134C10

public static void Fill<T>(T[] array, T value, int startIndex, int count)
{
	if (array == null)
	{
		ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
	}

	if ((uint)startIndex > (uint)array.Length)
	{
		ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_IndexMustBeLessOrEqual();
	}

	if ((uint)count > (uint)(array.Length - startIndex))
	{
		ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
	}

	if (!typeof(T).IsValueType && array.GetType() != typeof(T[]))
	{
		for (int i = startIndex; i < startIndex + count; i++)
		{
			array[i] = value;
		}
	}
	else
	{
		ref T first = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)startIndex);
		new Span<T>(ref first, count).Fill(value);
	}
}
posted @ 2025-05-07 10:23  BackSword  阅读(58)  评论(0)    收藏  举报