Why Selected event handling should be banned
So… Lately, admins of a web application I wrote several years ago got my attention for claiming the app getting slow. Now, as I, as a regular user of the same app, never noticed any performance issues, I decided to investigate. First problem I encountered was that integration and testing environment had way too little data to be presentable. A talk with our DBA sorted that out for me. Next, it was time for performance testing and locating the problematic code section.
Problem description
So, I started performance testing the application and it did seem to work ok-ish until I hit that Admin mode button. That button, at one point, took about 45 seconds to do, what is supposed to do: display all information as needed by application admins. Now, the application is calculation heavy, so I first thought this was due to high amount of data, but I checked SQL statements and none ran longer than 0.5 seconds, which is OK for a query that returns presentable data from 20K something rows of highly normalized data table. Hence, I knew it was something in the code. Probably something I did in a hurry and forgot to alter later on. I did manage, to narrow the problem down to one tab of a web page.
On this tab, there is this grid (or Telerik RadGrid to be precise) which is tied to ObjectDataSource which obtains data from a typed DataSet connected to DB2 database. Nothing weird, right? Except…
Problem located
…this data source had a Selected event handler tied to it. And this handler did some minor calculations on three columns returned. For each of 20K rows. And this is where post title comes in. Handling Selected event for doing calculations on any data source, larger than 100 rows should be banned, and developer shot at the spot! “But Why?”, you ask. Well, RadGrid for instance (and I am quite sure, you want the same behavior in GridView) does lazy loading. Meaning, that if you have 20K rows and you want to display them in pages with size of 20 items, RadGrid will load only 20 rows that should be displayed, leaving all others be. However, by manipulating Selected event handler, a calculation was done on all 20K rows each and every time data source got selected, which in turn caused a huge page load time.
Problem solved
As I wanted calculations to only happen on items displayed, I moved code from data source Selected event handler to RadGrid’s ItemDataBound event handler. Now, application loads all data displayed in about 3 seconds, no matter how much data there is.
Leave a Reply