Home > Back-end >  Should I dispose of manually a Dictionary data structure after I am done using it?
Should I dispose of manually a Dictionary data structure after I am done using it?

Time:10-24

Is it worth the effort to try and actively dispose of the Dictionary in this code, or just leave it to managed garbage collection?

private void LogReprocessTsk(List<ReprocessTsk> reprocessTsks)
{
    foreach (ReprocessTsk reprocessTsk in reprocessTsks)
    {
        Dictionary<string, string> logMessage = new Dictionary<string, string>
        {
            { "Message", "insert into REPROCESS_TSK - parentId changed" },
            { "TSKLOC", reprocessTsk.TSKLOC },
            { "CRS", reprocessTsk.CRS.ToString() },
            { "PROCESSED", reprocessTsk.PROCESSED.ToString() },
            { "OldParentId", reprocessTsk.OldParentId },
            { "NewParentId", reprocessTsk.NewParentId }
        };

        _logger.LogInformation(JsonConvert.SerializeObject(logMessage));
    }
}

CodePudding user response:

The garbage collector does its job very well and there is no reason to force a premature garbage collection. The dictionary gets out of the scope of the loop anyway at each iteration and becomes automatically a candidate for garbage collection.

You can minimize the number of object creations if you declare only one dictionary before the loop and clear it after use.

var logMessage = new Dictionary<string, string>();
foreach (ReprocessTsk reprocessTsk in reprocessTsks) {
    logMessage.Add("Message", "insert into REPROCESS_TSK - parentId changed");
    logMessage.Add("TSKLOC", reprocessTsk.TSKLOC);
    logMessage.Add("CRS", reprocessTsk.CRS.ToString());
    logMessage.Add("PROCESSED", reprocessTsk.PROCESSED.ToString());
    logMessage.Add("OldParentId", reprocessTsk.OldParentId);
    logMessage.Add("NewParentId", reprocessTsk.NewParentId);

    _logger.LogInformation(JsonConvert.SerializeObject(logMessage));
    logMessage.Clear();
}

Since you are using the same keys at each foreach iteration, yet another possibility is to re-assign the new values to the same dictionary key.

var logMessage = new Dictionary<string, string>();
foreach (ReprocessTsk reprocessTsk in reprocessTsks) {
    logMessage["Message"] = "insert into REPROCESS_TSK - parentId changed";
    logMessage["TSKLOC"] = reprocessTsk.TSKLOC;
    logMessage["CRS"] = reprocessTsk.CRS.ToString();
    logMessage["PROCESSED"] = reprocessTsk.PROCESSED.ToString();
    logMessage["OldParentId"] = reprocessTsk.OldParentId;
    logMessage["NewParentId"] = reprocessTsk.NewParentId;

    _logger.LogInformation(JsonConvert.SerializeObject(logMessage));
}

Note that the dictionary indexer creates non existing entries and replaces existing ones. See: the remarks section for the Dictionary<TKey,TValue>.Item[TKey] Property.

  • Related