如何初始化在C#中的整数数组 [英] How to initialize integer array in C#

查看:113
本文介绍了如何初始化在C#中的整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
   C#精益初始化int数组

基本上我想知道是否有一个比较有效的code比如下

Basically I would like to know if there is a more efficent code than the one shown below

    private static int[] GetDefaultSeriesArray(int size, int value)
    {
        int[] result = new int[size];
        for (int i = 0; i < size; i++)
        {
            result[i] = value;
        }
        return result;
    }

在这里的大小可以变化从10到15万对于小数组是不是一个问题,但应该有更好的方式来做到以上。 我使用VS2010(.NET 4.0)

where size can vary from 10 to 150000. For small arrays is not an issue, but there should be a better way to do the above. I am using VS2010(.NET 4.0)

推荐答案

这可以提高速度的方法之一是利用 Array.Copy 。它们也能够工作在一个较低的水平,其中它的散装分配较大的存储部。

One way that you can improve speed is by utilizing Array.Copy. It's able to work at a lower level in which it's bulk assigning larger sections of memory.

按配料的任务你可以最终从一个部分阵列复制到自身。

By batching the assignments you can end up copying the array from one section to itself.

在此之上,批次本身可以相当有效地paralleized

On top of that, the batches themselves can be quite effectively paralleized.

下面是我的初始code了。在我的机器(其中只有两个核心)与大小的样品阵列10万个项目,我得到一个15%左右的速度提升。你需要玩的批量大小(尽量留在你的页大小的倍数,以保持其高效的),以调整它到你项目的大小。对于较小的阵列,它会最终几乎等同于你的code,因为它不会让过去填补了第一批,但它也不会是(明显),在这种情况下无​​论是雪上加霜。

Here is my initial code up. On my machine (which only has two cores) with a sample array of size 10 million items, I was getting a 15% or so speedup. You'll need to play around with the batch size (try to stay in multiples of your page size to keep it efficient) to tune it to the size of items that you have. For smaller arrays it'll end up almost identical to your code as it won't get past filling up the first batch, but it also won't be (noticeably) worse in those cases either.

private const int batchSize = 1048576;
private static int[] GetDefaultSeriesArray2(int size, int value)
{

    int[] result = new int[size];

    //fill the first batch normally
    int end = Math.Min(batchSize, size);
    for (int i = 0; i < end; i++)
    {
        result[i] = value;
    }

    int numBatches = size / batchSize;

    Parallel.For(1, numBatches, batch =>
    {
        Array.Copy(result, 0, result, batch * batchSize, batchSize);
    });

    //handle partial leftover batch
    for (int i = numBatches * batchSize; i < size; i++)
    {
        result[i] = value;
    }

    return result;
}

这篇关于如何初始化在C#中的整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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