Showing posts with label IEnumerable. Show all posts
Showing posts with label IEnumerable. Show all posts

Wednesday, May 24, 2017

Possible Multiple Enumeration of IEnumerable

If you have worked with IEnumerable and using ReSharper, then you may land up into this warning, "Possible Multiple Enumeration of IEnumerable". So, what this warning is all about?
Well, before proceeding further, let’s see how we can store something into IEnumerable object .
IEnumerable items = GetAllItems()
So, above code itself speaks that items is a variable of type IEnumerable which will hold some values/objects we can iterate through.
Now here lies the performance hit, which is also indicated in the form of ReSharper warning. This performance hit may not be significant for a small number of items. But this can be noticed while dealing with a huge number of items.
Reason behind this is, whenever you are iterating through items collection, GetAllItems method will be called for the same number of times.
Solution: It is always good to materialized the result in a list or array like below:
IEnumerable items = GetAllItems().ToList()

Once you are done with mentioned code changes, you will notice that above warning doesn't exist any more.
Hope you like this small post.

Wednesday, October 16, 2013

Best Practices for ORM

Although everyone puts their complete effort to develop the best software, sometimes bad things happen. But to be on safer side we can take some precautionary measures. Well, today I want to share some of the best practices which needs to be followed while dealing with any ORMs (Object Relational Models). Most of these are common among many of the relational databases.
  1. Exception handling: One should handle only those exceptions which need to be handled, and let all others pass through. For example, if you want to handle a connection issue you should do this by catching the specific exceptions, but don't use a catch all on Exceptions with the clause "just in case" because it may lead to high performance issues.
  2. USING: As many of us know, that USING automatically handles dispose functionality. But this statement doesn’t work all the time, especially in the case of database connections. If you want to try it out, then run some overnight processes using windows services. Although USING handles it most of the time it is always a good practice to close database handles/connections manually.
  3. Prefer compiled LINQ queries: Compiling a query once and executing it several times can lead to high performance gains. Such queries are useful, especially when the same query needs to be accomplished numerous times for innumerable parameters. The syntax for that is: MORE...