We, as developers, get lost in getting a feature complete within a time-frame and negate performance most of the time. Currently, I am working on an application where I was requested to improve performance. A page was taking around 14-15s to get loaded. I brought it down to 4-5s although it is still a lot to wait. Here are some things that impacted performance of application and how I sorted it out
1. Lazy-loading everywhere
We used Entity Framework as ORM. In order to process data, we had couple of foreach statements and nested loops . Inside loop, properties of referenced entities and collections were manipulated . Loading such datas eagerly reduced around 100 queries.
2. Automapper used everywhere
Automapper was used extensively in our application. Suppose we had an Address Entity and it had reference to State entity which further had reference to Province entity , we mapped Address entity to AddressViewModel using automapper. Even when I needed detail of Address entity in AddressViewModel, it would map all details of references in AddressViewModel. One way to get rid of it was to configure Automapper in a way to exclude mapping references of entity but that would cause our application to break since it was used elsewhere. Mapping only required references helped to improve performance.
3. Selecting every fields from Database
Even if only some fields in a table were needed, every fields were retrieved from database. Some of the columns stored large amount of datas which resulted in weak performance. Selecting only the required fields improved performance by some margin.
4. Less Use of TryParse
In order to parse Enum from string or int , code used to wrapped inside Try/Catch block . If exception was caught, do something. Exceptions are meant to be unintentional but we depend on exceptions to perform an action. Changing those statements to use TryParse improved readability and performance slightly.
5. Unaware of SelectMany querying pattern
Whenever we needed a reference inside collections , we did SelectMany . Our common misconception was SelectMany does a single query to database and retrieved data. Using a profiler showed more number of queries than expected. Suppose , we had 5 items in collection and we used SelectMany to get references inside a collection, it did 5 queries where only 1 was expected. At the end, our solution was to issue a single query to required reference table.
That's all for now.
Happy Coding !!
Top comments (0)