c# - 快速迭代多维字符串数组

标签 c# unsafe

我正在尝试找出迭代多维 C# 数组的最快方法。我已经剥离了所有域代码以专注于问题。目前,它的执行时间为 1.86 秒,在这段时间内执行了大约 25,000,000 次迭代,处理了 5000 个数组元素。我为自己设定的目标是在 2 天内尽可能降低 1.86s :-)

在现实世界中,需要处理的面积更像是 50,000²。

我尝试过使用 PLINQ,但似乎线程开销实际上使它变慢了(达到 3.48 秒)。

我认为不安全的 C# 可能是可行的方法,但是,在我走这条路之前,我会很感激任何关于如何提高性能的想法?我以前没有做过不安全的 C#,所以我不确定这是否会提高性能?!

Console.WriteLine("started");
        var sw = System.Diagnostics.Stopwatch.StartNew();
        long iterations = 0;
        string[] data = new string[5000];
        string[] data2 = new string[5000];
        string[] data3 = new string[5000];

        int ubound = data.GetUpperBound(0);
        for (int i = 0; i <= ubound; i++)
        {
            string d1 = data[i];
            string d2 = data2[i];
            string d3 = data3[i];

            for (int j = 0; j < ubound; j++)
            {
                string e1 = data[j];
                string e2 = data2[j];
                string e3 = data3[j];
                Interlocked.Increment(ref iterations);
            }

            Interlocked.Increment(ref iterations);
        }
        Console.WriteLine("Finished {0} iterations in {1} seconds", iterations, sw.Elapsed.TotalSeconds);

最佳答案

代替多维数组,使用平面数组并使用数学来解决它:

Console.WriteLine("started");
var sw = System.Diagnostics.Stopwatch.StartNew();
long iterations = 0;

var width=5000;
var height=3;
string[] data = new string[width*height];
for (int i = 0; i < width; i++)
{
    string d1 = data[i];
    string d2 = data[width+i];
    string d3 = data[width*2+i];

    for (int j = 0; j < width; j++)
    {
        string e1 = data[j];
        string e2 = data[width+j];
        string e3 = data[width*2+j];
        Interlocked.Increment(ref iterations);
    }
    //});

    Interlocked.Increment(ref iterations);
}
Console.WriteLine("Finished {0} iterations in {1} seconds", iterations, sw.Elapsed.TotalSeconds);

关于c# - 快速迭代多维字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11891788/

相关文章:

c# - 使用 C# MongoDB 将 Int 转换为 String?

uikit - 检索 UIImage 的像素 alpha 值 (MonoTouch)

xml - 以安全的 Rust 方式切片 XML 字符串

c# - C# 中的 ref 和 out 是否与 C++ 中的指针相同?

c# - 使用 dapper 替换成熟的 OR/M

c# - 如何在 Visual C# 中获取数组中第二大的数字?

c# - 试图把我的头缠绕在线程上

c# - 帮助为我的类创建一个基本接口(interface)

C#:通过反射检索和使用 IntPtr*

pointers - 如何从原始指针创建一个 ?Sized 类型?