两个暗淡阵列到数据表转换的最佳性能

时间:2017-12-07 02:53:13

标签: c# arrays datatable

我一直在寻找一种优化方法来转换类型为

的方阵

加倍[,]

到DataTable

我抬头看着互联网,找不到比我方法中当前实现的更快的方法,这取决于两个嵌套的for循环。

问题在于性能非常糟糕。我的输入数组可以是每个维度中500到15000个元素的任何数组。 (数学可能很吓人)......

这意味着使用当前方法完成转换可能需要很长时间。

我正在考虑使用一些非托管代码甚至汇编代码来提高性能,但我不知道该怎么做..

我当前的代码就是这个......

// helper method to get row as a string array    
private static string[] GetRowFromArray(double[,] array, int column )

{

int dim = array.GetUpperBound(0) +1;

string[] row = new string[dim];

for(int i = 0; i < dim; i++)

{

    row[i] = array[i, column].ToString();

}

return row;

}


//the static extension method used to convert the array to datatable

public static DataTable ToDataTable(this double[,] array)

{

DataTable dt = new DataTable();

int rowsCount = array.GetUpperBound(0) + 1;

int colsCount = array.GetUpperBound(1) + 1;

int i = 0;

while (i < colsCount)

{

   dt.Columns.Add(); i++;

}

int ii = 0;

while (ii < rowsCount)

{

    string[] a = GetRowFromArray(array, ii);

    dt.Rows.Add(a);

    ii++;

}

return dt;

}

有关如何优化此功能以使其运行更快的任何想法。

只是旁注,数组是方阵,因此ColumnsCount = RowsCount

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:0)

好吧,你可以并行化它。在示例代码中,创建维度任务的数量并且并行运行。

    private static string[] GetRowFromArray(double[,] array, int column)
    {
        int dim = array.GetUpperBound(0) + 1;
        string[] row = new string[dim];

        //for (int i = 0; i < dim; i++)
        Parallel.For(0, dim, i =>
        {
            row[i] = array[i, column].ToString();
        });

        return row;
    }

您可以通过

控制并行度
        ParallelOptions options = new ParallelOptions();
        options.MaxDegreeOfParallelism = dim;

        Parallel.For(0, dim, options, i =>
        {
            row[i] = array[i, column].ToString();
        });

https://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.for(v=vs.110).aspx

答案 1 :(得分:0)

您可以通过...优化代码。

  1. 消除DataTable(只需直接使用数组)。
  2. 使用锯齿状数组并消除双向字符串转换。
  3. 使用DataTable是导致性能不佳的最重要因素。但是,我们假设您必须使用DataTable。在这种情况下,您的主要问题是需要构造一个单维数组以提供给DataRowCollection.Add()方法。

    通过使用锯齿状数组,您可以直接提供单维数组。这使代码速度提高了近7倍。

    let autocompleteController = GMSAutocompleteViewController()
    let searchBarTextAttributes: [NSAttributedString.Key : AnyObject] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.white, NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): UIFont.systemFont(ofSize: UIFont.systemFontSize)]
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes
    

    我相信你在GetRowFromArray函数中转换了行和列。如果多维数组不是正方形,则这是显而易见的。我意识到你说的是,但是我为x和y写了不同长度的代码。

    这是我的代码。

    Original poster's code ran in 15679 msec.
    My code ran in 2261 msec.
    My code is 6.94x faster.
    
相关问题