使用同一元素的多个副本初始化C#数组 [英] Initializing a C# array with multiple copies of the same element

查看:63
本文介绍了使用同一元素的多个副本初始化C#数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在C ++标准模板库(STL)中,可以使用以下构造函数创建一个由相同元素的多个副本组成的矢量:

In the C++ Standard Template Library (STL), it is possible for example to create a vector consisting of multiple copies of the same element, using this constructor:

std::vector<double> v(10, 2.0);

这将创建一个10倍的向量,最初设置为2.0.

This would create a vector of 10 doubles, initially set to 2.0.

我想在C#中做类似的事情,更具体地说,创建一个 n 双精度数组,并将所有元素初始化为相同的值 x .

I want to do a similar thing in C#, more specifically creating an array of n doubles with all elements initialized to the same value x.

我根据通用集合和LINQ提出了以下一种方法:

I have come up with the following one-liner, relying on generic collections and LINQ:

double[] v = new double[n].Select(item => x).ToArray();

但是,如果一个局外人会阅读这段代码,我认为代码实际上不会立即生效.我还担心性能,我想通过 for 循环初始化数组元素会更快(尽管我没有检查).有人知道更干净和/或更有效的方法来执行此任务吗?

However, if an outsider would read this code I don't think it would be immediately apparent what the code actually does. I am also concerned about the performance, I suppose it would be faster to initialize the array elements via a for loop (although I haven't checked). Does anybody know of a cleaner and/or more efficient way to perform this task?

推荐答案

这怎么办?

double[] v = Enumerable.Repeat(x, n).ToArray();

我只是做了一个小型基准测试;创建一个1000个数组(每个数组包含100000个元素),使用循环的速度是Enumerable.Repeat的三倍.

I just did a small benchmark; to create 1000 arrays of 100000 elements each, using a loop is about 3 times faster that Enumerable.Repeat.

Repeat 
00:00:18.6875488 

Loop 
00:00:06.1628806 

因此,如果性能至关重要,则应该选择循环.

So if performance is critical, you should prefer the loop.

这篇关于使用同一元素的多个副本初始化C#数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆