To boost performance, it is advisable to give preference to the use of concrete types whenever feasible. An illustrative example highlighting this point can be found in the Entity Framework source code:
private IDictionary GetContextInfoImpl(string? contextType)
{
var info = ContextOperations.GetContextInfo(contextType);
return new Hashtable
{
["Type"] = info.Type,
["ProviderName"] = info.ProviderName,
["DatabaseName"] = info.DatabaseName,
["DataSource"] = info.DataSource,
["Options"] = info.Options
};
}
This guideline suggests upgrading the type of specific local variables, fields, properties, method parameters, and method return types from interfaces or abstract types to concrete types whenever possible. Utilizing concrete types enhances the quality of generated code by reducing virtual or interface dispatch overhead and enabling inlining.
To address this issue, you can easily modify the return type to Hashtable
, as demonstrated below:
private Hashtable GetContextInfoImpl(string? contextType)
{
var info = ContextOperations.GetContextInfo(contextType);
return new Hashtable
{
["Type"] = info.Type,
["ProviderName"] = info.ProviderName,
["DatabaseName"] = info.DatabaseName,
["DataSource"] = info.DataSource,
["Options"] = info.Options
};
}
When I setup the CA1859 code analysis in my .editorConfig it looks like this:
dotnet_diagnostic.CA1859.severity = warning
Summary
While reviewing the Entity Framework codebase I utilized for this article, I discovered 154 occurrences where the code needs to be fixed so performance can be increased.
For further guidance and insights, I highly recommend obtaining a copy of my book, “Rock Your Code: Coding Standards for Microsoft .NET” available on Amazon.com. Additionally, to explore more performance tips for .NET, I encourage you to acquire the 3rd edition of “Rock Your Code: Code & App Performance for Microsoft .NET” also available on Amazon.com.
To analyze your code using the same settings I used in these articles, I encourage you to incorporate my EditorConfig file. It can be found at the following link: https://bit.ly/dotNetDaveEditorConfig. I update this file quarterly, so remember to keep yours up to date as well. I hope you will check out my OSS project Spargine by using this link: https://bit.ly/Spargine.
Please feel free to leave a comment below. I would appreciate hearing your thoughts and feedback.
Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave
© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.