Fastest method in .NET to store dictionary of dictionaries into a rectangular 2-D array

I have a very large dictionary of dictionaries where both layers are keyed on strings with inside dictionary representing a row with heterogenous values (Strings and Doubles) that I’d like to store into a 2d array of objects to populate into an API (Excel etc.). I have two questions:

  1. What is the fastest way to do this in .NET 4.6.1?
  2. Why would populating this array using the following code take much longer than creating the dictionary of dictionaries in the first place (via reflection on a list of type instances) for about 1mm rows and 14 columns?
public void FillDataFrameWithDD(Dictionary<string, Dictionary<string, object>> inDD,
                                bool sanitizeType = true,
                                bool tu = false,
                                bool doKeyCheck = true)
{
    if (inDD == null || inDD.Count == 0)
    {
        return;
    }

    this.Clear();

    var firstRow = inDD[inDD.Keys.First()];
    this.columnTranslator = new NameNumberTranslator(inDD, false);
    this.rowTranslator = new NameNumberTranslator(inDD, true);
    long numRows = inDD.Count;
    long numCols = firstRow.Count; // uses first dictionary as representative
    object[,] dMatrix = new object[numRows, numCols];

    // Populate DataMatrix
    long fullWorkSize = numRows * numCols;
    long loopCount = numRows;

    long? multiThreadedLoopCountThreshold = Get_FOR_LOOP_COUNT_Threshold4Multithreading(totalWork_IterationCount: fullWorkSize,
                                                                                      outerForLoop_IterationCount: loopCount);
    string[] ColNameArray = this.columnTranslator.NameArray;

    Loop_SUB_N_Times(i =>
    {
        var currentRow = inDD[inDD.Keys.ElementAt(i)];

        if (doKeyCheck)
        {
            for (int j = 0; j < numCols; j++)
            {
                string stringKey = ColNameArray[j];

                dMatrix[i, j] = currentRow.ContainsKey(stringKey) ? currentRow[stringKey] : null;
            }
        }
        else
        {
            for (int j = 0; j < numCols; j++)
            {
                string stringKey = ColNameArray[j];

                dMatrix[i, j] = currentRow[stringKey];
            }
        }

    }, N:loopCount, N_Threshold4MultiThreading:multiThreadedLoopCountThreshold);

    this.frameMatrix = new DataMatrix();
    this.frameMatrix.ArrayValue = dMatrix;

    if (sanitizeType)
    {
        this.Sanitize();
    }

    if (tu)
    {
        this.TUFrame();
    }
}

Note that I am using a simple method I wrote to crack for loops into multiple parallel tasks based on the loop index:

public void Loop_SUB_N_Times(Action<long> inSub, long N, long loopStartIndex = 0, long? loopEndIndex = default(Long?), long? numberOfThreads = default(Long?), ref Dictionary<long, string> inExceptionList = null, bool useHigherThreadPriority = true)
{
    long lLoopEndIndex;
    if (loopEndIndex == null)
        lLoopEndIndex = N - 1 + loopStartIndex;
    else
        lLoopEndIndex = loopEndIndex;

    List<PerThread_FOR_LOOP_COUNTER_BatchSplit_Boundaries> loopBatches = BatchSplit_FOR_LOOP_COUNTER_Boundaries_ForThreading(loopEndIndex: lLoopEndIndex, numberOfThreads: numberOfThreads, loopStartIndex: loopStartIndex);
    ConcurrentBag<Task> taskList = new ConcurrentBag<Task>();
    ConcurrentDictionary<long, string> exceptionList = new ConcurrentDictionary<long, string>();
    bool inExceptionList_NON_NULL = inExceptionList != null;

    try
    {
        long loopCount = 0;
        long batchCount = 0;
        foreach (var batch in loopBatches)
        {
            // ... needs local closure as loop index may change when thread runs...
            PerThread_FOR_LOOP_COUNTER_BatchSplit_Boundaries l_batch = batch;

            taskList.Add(Task.Run(() =>
            {
                try
                {
                    if (useHigherThreadPriority)
                        Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
                    long i;
                    for (i = l_batch.leftBoundary; i <= l_batch.rightBoundary; i++)
                    {
                        try
                        {
                            inSub(i);
                        }
                        catch (Exception ex)
                        {
                            if (inExceptionList_NON_NULL)
                                exceptionList.TryAdd(i, PrintExceptionMessage(ex));
                        }
                    }
                }
                catch (Exception ex)
                {
                }

                finally
                {
                    if (useHigherThreadPriority)
                        Thread.CurrentThread.Priority = ThreadPriority.Normal;
                }
            }));

            loopCount += batch.batchSize;
            batchCount += 1;
            if (batchCount % 2 == 1)
                Debug.Print($"Dispatched {loopCount} iterations of {N}... ({batch.numberOfThreads} threads)");
        }
    }
    catch (Exception ex)
    {
    }

    // NB: this line must be outside the try...catch block as we may hang otherwise.
    // NB: WaitAll blocks the thread.
    Task.WaitAll(taskList.Select(x => x).ToArray);

    if (inExceptionList_NON_NULL && exceptionList.Count > 0)
        inExceptionList = exceptionList.ToDictionary(x => x.Key, x => x.Value);
}

I used the above multithreaded method (spawning 6 tasks) and reflection to load the dictionary of dictionaries on an Intel Haswell 4790 on a list of type instances and it took only a few seconds for about 1mm entries with 14 properties each. However, converting that dictionary of dictionaries to a 2-D array is taking over 20 minutes…

1

If you are worried about performance profile your code. We can make guesses about performance, but it is much more reliable to use the available tools to get actual data that can be relied upon.

If this takes 20min, chances are there are something weird going on that you do not understand. Profiling and is critical to understand what this is. Chances are you will be spending 99% of the time in some part you never even suspected was a problem.

Some observations.

  1. I always recommend doing multi threading last, after I’m reasonably confident all other improvements have been exhausted. Multithreading speeds up your code by at most your core count. Avoiding unnecessary or repeated work can give much larger benefit.
  2. I would strongly recommend using Parallel.For or Parallel.ForEach instead of rolling your own.
  3. Remove the thread priority parts, it will probably not help, and may cause problems.
  4. avoid .ElementAt(i) in performance sensitive code.
  5. Your code seem to assume that all rows have the same column keys. Are you 100% sure that this is true? You may want to do a inDD.SelectMany(r => r.Value.Keys).Distinct().ToList() to be sure you have all keys.
  6. Use TryGetValue if you are not sure the key exist.
  7. I would be careful to use object in high performance code, since it is a reference type. If you have really huge number of values it is often a good idea to use value types instead.

The simplest code to convert dictionaries to a 2D array I could come up with is this:

// generate test data
var data = new Dictionary<string, Dictionary<string, object>>();
var rowKeys = Enumerable.Range(0, 1_000_000).Select(i => i.ToString()).ToList();
var columnKeys = "abcdefghijklmnopqrst".Select(c => c.ToString()).ToList();
var rand = new Random();
foreach (var rowKey in rowKeys)
{
    var dict = new Dictionary<string, object>();
    data[rowKey] = dict;
    foreach (var columnKey in columnKeys)
    {
        dict[columnKey] = rand.Next();
    }
}
// run the conversion code
var sw = Stopwatch.StartNew();
var result = new object[rowKeys.Count, columnKeys.Count];
for (var i = 0; i < rowKeys.Count; i++)
{
    var rowkey = rowKeys[i];
    var dict = data[rowkey];
    for (var j = 0; j < columnKeys.Count; j++)
    {
        var columnKey = columnKeys[j];
        result[i, j] = dict[columnKey];
    }
}

sw.Stop();

Console.WriteLine($"{sw.ElapsedMilliseconds}ms");

This runs in ~500ms on my system.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật