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:
- What is the fastest way to do this in .NET 4.6.1?
- 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.
- 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.
- I would strongly recommend using
Parallel.For
orParallel.ForEach
instead of rolling your own. - Remove the thread priority parts, it will probably not help, and may cause problems.
- avoid
.ElementAt(i)
in performance sensitive code. - 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. - Use TryGetValue if you are not sure the key exist.
- 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