简体   繁体   English

最有效的Array.Resize方法,默认值不是“ 0”吗?

[英]Most efficient way to Array.Resize with something other than “0” as default value?

I'd like to resize an array, however I don't want all the appended values to be zero. 我想调整数组的大小,但是我不希望所有附加值都为零。

Array.Resize(ref range, range.Length + grow);

If you assume that the appended length is always a multiple of 4 bytes (just enough to hold a float), what is the best way to fill this up with either float.MaxValue or float.MinValue ? 如果您假定附加长度始终是4个字节的倍数(刚好足以容纳float),那么用float.MaxValuefloat.MinValue填充此长度的最佳方法是什么?

Just loop through the added items and assign the value to it. 只需循环浏览添加的项目并为其分配值。 The compiler will produce code to only do the range checking of the array indexes once outside the loop, so the loop will be very efficient. 一旦在循环外,编译器将产生代码以仅对数组索引进行范围检查,因此循环将非常有效。

int oldSize = range.Length;
Array.Resize(ref range, range.Length + grow);
for (int i = oldSize; i < range.Length; i++) {
  range[i] = float.MinValue;
}

You should be aware that the Array.Resize doesn't actually resize the array, but it creates a new array with the desired size and copies the data from the original array. 您应该意识到Array.Resize实际上并没有调整数组的大小,但是会创建一个具有所需大小的新数组,并从原始数组中复制数据。 So, if you want a way to resize a collection efficiently, you shouldn't use an array at all. 因此,如果您想要一种有效地调整集合大小的方法,则根本不应该使用数组。 Depending on your needs something like a List, a List of arrays, or a LinkedList would probably be better. 根据您的需求,诸如列表,数组列表或LinkedList之类的内容可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM