Click here to Skip to main content
Click here to Skip to main content

ASP.NET Best Practices for High Performance Applications

By , 21 Mar 2006
 

Introduction

ASP.NET is much more powerful than classic ASP, however it is important to understand how to use that power to build highly efficient, reliable and robust applications. In this article, I tried to highlight the key tips you can use to maximize the performance of your ASP.NET pages. The list can be much longer, I am only emphasizing the most important ones.

1. Plan and research before you develop

Research and investigate how .NET can really benefit you. .NET offers a variety of solutions on each level of application design and development. It is imperative that you understand your situation and pros and cons of each approach supported by this rich development environment. Visual Studio is a comprehensive development package and offers many options to implement the same logic. It is really important that you examine each option and find the best optimal solution suited for the task at hand. Use layering to logically partition your application logic into presentation, business, and data access layers. It will not only help you create maintainable code, but also permits you to monitor and optimize the performance of each layer separately. A clear logical separation also offers more choices for scaling your application. Try to reduce the amount of code in your code-behind files to improve maintenance and scalability.

2. String concatenation

If not handled properly, String Concatenation can really decrease the performance of your application. You can concatenate strings in two ways.

  • First, by using string and adding the new string to an existing string. However, this operation is really expensive (especially if you are concatenating the string within a loop). When you add a string to an existing string, the Framework copies both the existing and new data to the memory, deletes the existing string, and reads data in a new string. This operation can be very time consuming and costly in lengthy string concatenation operations.
  • The second and better way to concatenate strings is using the StringBuilder Class. Below is an example of both approaches. If you are considering doing any type of String Concatenation, please do yourself a favor and test both routines separately. You may be surprised at the results.

    'Concatenation using String Class 
    Response.Write("<b>String Class</b>")
    Dim str As String = ""
    Dim startTime As DateTime = DateTime.Now
    Response.Write(("<br>Start time:" + startTime.ToString()))
    Dim i As Integer
    For i = 0 To 99999
    str += i.ToString()
    Next i
    Dim EndTime As DateTime = DateTime.Now
    Response.Write(("<br>End time:" + EndTime.ToString()))
    Response.Write(("<br># of time Concatenated: " + i.ToString))

    Results: Took 4 minutes and 23 Seconds to to complete 100,000 Concatenations.

    String Class
    • Start time: 2/15/2006 10:21:24 AM
    • End time: 2/15/2006 10:25:47 AM
    • # of time Concatenated: 100000

    'Concatenation using StringBuilder
     Response.Write("<b>StringBuilder Class</b>")
     Dim strbuilder As New StringBuilder()
     Dim startTime As DateTime = DateTime.Now
     Response.Write(("<br>Start time:" + startTime.ToString()))
     Dim i As Integer
     For i = 0 To 99999
     strbuilder.Append(i.ToString())
     Next i
     Dim EndTime As DateTime = DateTime.Now
     Response.Write(("<br>Stop time:" + EndTime.ToString()))
     Response.Write(("<br># of time Concatenated: " + i.ToString))

    Results: Took less than a Second to complete 100,000 Concatenations.

    StringBuilder Class
    • Start time: 2/15/2006 10:31:22 AM
    • Stop time:2/15/2006 10:31:22 AM
    • # of time Concatenated: 100000

This is one of the many situations in which ASP.NET provides extremely high performance benefits over classic ASP.

3. Avoid round trips to the server

You can avoid needless round trips to the Web Server using the following tips:

  • Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed. I think Scott's article gave great information on how to implement Ajax Atlas and <atlas:updatepanel> control.
  • Use Client Side Scripts. Client site validation can help reduce round trips that are required to process user's request. In ASP.NET you can also use client side controls to validate user input.
  • Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is loaded the first time and not in response to client postbacks.

    If Not IsPostBack Then 
    LoadJScripts()
    End If
  • In some situations performing postback event handling are unnecessary. You can use client callbacks to read data from the server instead of performing a full round trip. Click here for details.

4. Save viewstate only when necessary

ViewState is used primarily by Server controls to retain state only on pages that post data back to themselves. The information is passed to the client and read back in a hidden variable. ViewState is an unnecessary overhead for pages that do not need it. As the ViewState grows larger, it affects the performance of garbage collection. You can optimize the way your application uses ViewState by following these tips:

Situation when you don't need ViewState

ViewState is turned on in ASP.NET by default. You might not need ViewState because your page is output-only or because you explicitly reload data for each request. You do not need ViewState in the following situations:

  • Your page does not post back. If the page does not post information back to itself, if the page is only used for output, and if the page does not rely on response processing, you do not need ViewState.
  • You do not handle server control events. If your server controls do not handle events, and if your server controls have no dynamic or data bound property values, or they are set in code on every request, you do not need ViewState.
  • You repopulate controls with every page refresh. If you ignore old data, and if you repopulate the server control each time the page is refreshed, you do not need ViewState.

Disabling viewstate

There are several ways to disable ViewState at various levels:

  • To disable ViewState for a single control on a page, set the EnableViewState property of the control to false.
  • To disable ViewState for a single page, set the EnableViewState attribute in the @ Page directive to false. i.e.

    <%@ Page EnableViewState="false" %> 
  • To disable ViewState for a specific application, use the following element in the Web.config file of the application:

    <pages enableViewState="false" />
  • To disable ViewState for all applications on a Web server, configure the <pages> element in the Machine.config file as follows:

    <pages enableViewState="false" />

Determine the size of your ViewState

By enabling tracing for the page, you can monitor the ViewState size for each control. You can use this information to determine the optimal size of the ViewState or if there are controls in which the ViewState can be disabled.

5. Use session variables carefully

Avoid storing too much data in session variables, and make sure your session timeout is reasonable. This can use a significant amount of server memory. Keep in mind that data stored in session variables can hang out long after the user closes the browser. Too many session variables can bring the server on its knees. Disable session state, if you are not using session variables in the particular page or application.

  • To disable session state for a page, set the EnableSessionState attribute in the @ Page directive to false.i.e.

    <%@ Page EnableSessionState="false" %> 
  • If a page requires access to session variables but will not create or modify them, set the EnableSessionState attribute in the@ Page directive to ReadOnly. i.e.

    <%@ Page EnableSessionState="ReadOnly" %>   
  • To disable session state for a specific application, use the following element in the Web.config file of the application.

    <sessionState mode='Off'/>
  • To disable session state for all applications on your Web server, use the following element in the Machine.config file:

    <sessionState mode='Off'/>

6. Use Server.Transfer

Use the Server.Transfer method to redirect between pages in the same application. Using this method in a page, with Server.Transfer syntax, avoids unnecessary client-side redirection. Consider Using Server.Transfer Instead of Response.Redirect. However, you cannot always just replace Response.Redirect calls with Server.Transfer. If you need authentication and authorization checks during redirection, use Response.Redirect instead of Server.Transfer because the two mechanisms are not equivalent. When you use Response.Redirect, ensure you use the overloaded method that accepts a Boolean second parameter, and pass a value of false to ensure an internal exception is not raised. Also note that you can only use Server.Transfer to transfer control to pages in the same application. To transfer to pages in other applications, you must use Response.Redirect.

7. Use server controls when appropriate and avoid creating deeply nested controls

The HTTP protocol is stateless; however, server controls provide a rich programming model that manage state between page requests by using ViewState. However nothing comes for free, server controls require a fixed amount of processing to establish the control and all of its child controls. This makes server controls relatively expensive compared to HTML controls or possibly static text. When you do not need rich interaction, replace server controls with an inline representation of the user interface that you want to present. It is better to replace a server control if:

  • You do not need to retain state across postbacks
  • The data that appears in the control is static or control displays read-only data
  • You do not need programmatic access to the control on the server-side

Alternatives to server controls include simple rendering, HTML elements, inline Response.Write calls, and raw inline angle brackets (<% %>). It is essential to balance your tradeoffs. Avoid over optimization if the overhead is acceptable and if your application is within the limits of its performance objectives.

Deeply nested hierarchies of controls compound the cost of creating a server control and its child controls. Deeply nested hierarchies create extra processing that could be avoided by using a different design that uses inline controls, or by using a flatter hierarchy of server controls. This is especially important when you use controls such as Repeater, DataList, and DataGrid because they create additional child controls in the container.

8. Choose the data viewing control appropriate for your solution

Depending on how you choose to display data in a Web Forms page, there are often significant tradeoffs between convenience and performance. Always compare the pros and cons of controls before you use them in your application. For example, you can choose any of these three controls (DataGrid, DataList and Repeater) to display data, it's your job to find out which control will provide you maximum benefit. The DataGrid control can be a quick and easy way to display data, but it is frequently the most expensive in terms of performance. Rendering the data yourself by generating the appropriate HTML may work in some simple cases, but customization and browser targeting can quickly offset the extra work involved. A Repeater Web server control is a compromise between convenience and performance. It is efficient, customizable, and programmable.

9. Optimize code and exception handling

To optimize expensive loops, use For instead of ForEach in performance-critical code paths. Also do not rely on exceptions in your code and write code that avoids exceptions. Since exceptions cause performance to suffer significantly, you should never use them as a way to control normal program flow. If it is possible to detect in code a condition that would cause an exception, do so. Do not catch the exception itself before you handle that condition. Do not use exceptions to control logic. A database connection that fails to open is an exception but a user who mistypes his password is simply a condition that needs to be handled. Common scenarios include checking for null, assigning a value to a String that will be parsed into a numeric value, or checking for specific values before applying math operations. The following example demonstrates code that could cause an exception and code that tests for a condition. Both produce the same result.

'Unnecessary use of exception
 Try
     value = 100 / number
Catch ex As Exception
    value = 0
End Try

' Recommended code
If Not number = 0 Then
    value = 100 / number
Else
    value = 0
End If

Check for null values. If it is possible for an object to be null, check to make sure it is not null, rather then throwing an exception. This commonly occurs when you retrieve items from ViewState, session state, application state, or cache objects as well as query string and form field variables. For example, do not use the following code to access session state information.

'Unnecessary use of exception
Try
value = HttpContext.Current.Session("Value").ToString
Catch ex As Exception
Response.Redirect("Main.aspx", False)
End Try
 
'Recommended code 
If Not HttpContext.Current.Session("Value") Is Nothing Then
value = HttpContext.Current.Session("Value").ToString
Else
Response.Redirect("Main.aspx", False)
End If

10. Use a DataReader for fast and efficient data binding

Use a DataReader object if you do not need to cache data, if you are displaying read-only data, and if you need to load data into a control as quickly as possible. The DataReader is the optimum choice for retrieving read-only data in a forward-only manner. Loading the data into a DataSet object and then binding the DataSet to the control moves the data twice. This method also incurs the relatively significant expense of constructing a DataSet. In addition, when you use the DataReader, you can use the specialized type-specific methods to retrieve the data for better performance.

11. Use paging efficiently

Allowing users to request and retrieve more data than they can consume puts an unnecessary strain on your application resources. This unnecessary strain causes increased CPU utilization, increased memory consumption, and decreased response times. This is especially true for clients that have a slow connection speed. From a usability standpoint, most users do not want to see thousands of rows presented as a single unit. Implement a paging solution that retrieves only the desired data from the database and reduces back-end work on the database. You should optimize the number of rows returned by the Database Server to the middle-tier web-server. For more information read this article to implement paging at the Database level. If you are using SQL Server 2000, please also look at this article.

12. Explicitly Dispose or Close all the resources

To guarantee resources are cleaned up when an exception occurs, use a try/finally block. Close the resources in the finally clause. Using a try/finally block ensures that resources are disposed even if an exception occurs. Open your connection just before needing it, and close it as soon as you're done with it. Your motto should always be "get in, get/save data, get out." If you use different objects, make sure you call the Dispose method of the object or the Close method if one is provided. Failing to call Close or Dispose prolongs the life of the object in memory long after the client stops using it. This defers the cleanup and can contribute to memory pressure. Database connection and files are examples of shared resources that should be explicitly closed.

Try
_con.Open()
Catch ex As Exception
Throw ex
Finally
If Not _con Is Nothing Then
_con.Close()
End If
End Try

13. Disable tracing and debugging

Before you deploy your application, disable tracing and debugging. Tracing and debugging may cause performance issues. Tracing and debugging are not recommended while your application is running in production. You can disable tracing and debugging in the Machine.config and Web.config using the syntax below:

<configuration>
   <system.web>
      <trace enabled="false" pageOutput="false" />
      <compilation debug="false" />
   </system.web>
</configuration>

14. Precompile pages and disable AutoEventWireup

By precompiled pages, users do not have to experience the batch compile of your ASP.NET files; it will increase the performance that your users will experience.

In addition, setting the AutoEventWireup attribute to false in the Machine.config file means that the page will not match method names to events and hook them up (for example, Page_Load). If page developers want to use these events, they will need to override the methods in the base class (for example, they will need to override Page.OnLoad for the page load event instead of using a Page_Load method). If you disable AutoEventWireup, your pages will get a slight performance boost by leaving the event wiring to the page author instead of performing it automatically.

15. Use stored procedures and indexes

In most cases you can get an additional performance boost by using compiled stored procedures instead of ad hoc queries.

Make sure you index your tables, and choose your indexes wisely. Try using Index Tuning Wizard and have it report to you what it thinks the best candidates for indexes would be. You don't have to follow all of its suggestions, but it may reveal things about your structure or data that will help you choose more appropriate indexes.

  • In SQL Server Management Studio (SQL Server 2005), highlight your query. Now from the Query menu, click Analyze Query in Database Engine Tuning Advisor.
  • You can do something similar in SQL Server 2000 to run the index tuning wizard? In Query Analyzer, highlight your query. From the Query menu, click Index Tuning Wizard.

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Ali Khan (OKC)
Web Developer
United States United States
Member
I work for Hertz Corporation as System Developer /Analyst and have exposure to various development environments, web applications, databases, along with information and project management techniques.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberamnk.info16 May '13 - 20:02 
very helpful article
GeneralMy vote of 5memberM.Shawamreh2 Apr '13 - 22:06 
Really Nice Article .. BIG Thanks Smile | :)
GeneralMy vote of 5memberHariPrasad katakam20 Feb '13 - 23:12 
Hello Ali Khan, very useful and important tips. Nice work and keep continue to share your thoughts. Just ignore Kikoz68 kind of people Smile | :)
GeneralMy vote of 4memberEduardo Ceratti27 Nov '12 - 6:47 
Have nice information about best practices
GeneralMy vote of 5memberGerard Castelló Viader31 Oct '12 - 6:29 
Very useful!
GeneralMy vote of 5memberrajyarr17 Dec '11 - 15:05 
Thanks bro
Generalwell done for your article, It helped us alot, Thank you very much!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!memberAWERT123200311 Mar '08 - 2:19 
well done!!!
GeneralUsing Block - 12. Explicitly Dispose or Close all the resourcesmemberrickstrand21 Feb '08 - 12:29 
Rather than the try catch finally block you could use a USING block
 
using (Connection con = new Connection())
{
make your magic
}
 
This will always dispose of your objects even in the case of exceptions....
GeneralException HandlingmemberChris L9 Dec '07 - 5:24 
Well it’s a common sense thing that crazy use of exception handling, raising unnecessary exceptions and not thinking about writing better code will cause extra overhead and things will slow down. Exceptions gather all the information e.g. where error happened, which method called which … etc.
 
I 100% agree with DarrenKopp and author of this article. It will definitely affect performance.
 
“When you throw an exception you stop current execution, you create a new object with data about the execution, and then you run any cleanup that is needed (garbage collection).
 
Architecturally speaking, you have to save all local variables, all parameters, current location, then jump to the code that handles the exception, which there is a very good chance will not be in cache, and if the program is large enough, won't be in memory, causing a need to read data from the hard drive”
 
And I also agree with Ali Khan
 
“I can give you hundreds of real world examples where you write code to avoid unnecessary exceptions. In any real world large application you will see hundred of lines of code to avoid exceptions/null references like…”
 
“What is the concept behind Data Validation Controls and Scripting Languages (like Java or VB Script)? Main purpose is to avoid unnecessary overhead, you should check user input for validity before start processing user request. This way you can also avoid unnecessary exceptions”
GeneralKikoz68 + BlackBerrymemberChipalino27 Nov '07 - 4:36 
I found myself not being in majority of this discussion because I actually agree on almost all Kikoz68's points. I have seen very similar article somewhere else. I do not know the author but it looks like it was just copied and pasted. Some people just copy stuff from books without understanding that most advices and practices from those books only good for homepage or a church voting page, not for real web app. I had very similar experience talking to business analysts/application architects/system architects with 2-3 wireless devices on their belts who carry themselves with a lot importance but what they really are - high class bullshitters. But they love to engage themselves into technology conversations.
And the last thing, everybody's favorite - exceptions. When i started to work with .NET I thought the same way Ali Khan is thinking - true/false, 0/1. On my second year with .NET I changed my approach to application exceptions.
I wander if Kikoz68 has a Blackberry. Wink | ;)

GeneralRe: Kikoz68 + BlackBerrymemberAli Khan (OKC)8 Dec '07 - 11:37 
“When i started to work with .NET I thought the same way Ali Khan is thinking - true/false, 0/1. On my second year with .NET I changed my approach to application exceptions”
 

My main idea behind avoiding and raising unnecessary exceptions was “Don’t completely depend on exceptions and write code that avoids exceptions”
 
I clearly mentioned that don’t completely depend on exception handling when you can write better code to avoid some exception.
 
Just like you did after 1st year, you will change your approach after your 2nd year with .NET also, and will agree /realize the importance of writing better code. I can give you hundreds of real world examples where you write code to avoid unnecessary exceptions. In any real world large application you will see hundred of lines of code to avoid exceptions/null references like

if (str != null)
if (obj != null)
if(comboBoxFont.SelectedItem != null)
if (string.IsNullOrEmpty(strName))
if (args.Data == null)
if (list.Count > 0)
 
Open your eyes and look at any real world application you are working on, you will find hundreds of similar lines of code to avoid exceptions. If you can’t find this type of code in your application then you need to go back to school and retake CS 101.
 
What is the concept behind Data Validation Controls and Scripting Languages (like Java or VB Script)? Main purpose is to avoid unnecessary overhead, you should check user input for validity before start processing user request. This way you can also avoid unnecessary exceptions.
 
If we should be completing relaying on exceptions handling and shouldn’t care about avoiding/raising unnecessary exceptions then why Microsoft added methods like string.IsNullOrEmpty in .NET framework? Do you thing that after your first year of .NET you learned more than the people who designed .NET framework.
 
“I do not know the author but it looks like it was just copied and pasted. Some people just copy stuff from books without understanding that most advices and practices from those books only good for homepage or a church voting page, not for real web app”
 
Well I know what I am talking about and I can defend what I wrote, however there is no way you can justify unnecessary use of exception. As I mentioned above, go find out any real world application that doesn’t use that kind of code. I wrote this article about 21 months ago, and listed some basic things to avoid unnecessary overhead for ASP.NET applications, why don’t you guys post the links to prove that I copied this article?
 
Keep in mind, these are basic concepts, and basic things are always important/straight whether you are creating a 10 pages or 100 pages website. They are implemented and used in all real world applications. Clear your basic concepts before talking about real world applications.
 
Some people try to show that they are so smart/experienced that everything written in books, articles has nothing to do with real world apps, and it doesn’t mean anything. They think that only they know what is right and wrong, in reality they are just illiterate and uneducated.
 
Muhammad Ali Khan
System Development Analyst
Hertz Corporation

QuestionKikoz68 you have problem?memberAMassani24 Nov '07 - 21:55 
Who the hell is this kikoz68 guy..
QuestionKikoz68 you have problem?memberdsmportal22 Nov '07 - 3:05 
Kikoz68 : why don't you write an article if you think or you claim to know more then Ali Khan? its very absurd to see people who don't appreciate what others are contributing to community.
 
Ali Khan: very well done and i enjoy reading your article... good job man....
 
Regards
John Mark
AnswerRe: Kikoz68 you have problem?memberAlex_Mish22 Nov '07 - 5:26 
John. You don't need to defend Ali Khan. Kikoz68 definitely needs to go through some anger management program of some sort. Still read carefully what he is saying. Can't wait for Ali Khan to reply.
 
Alex
AnswerRe: Kikoz68 you have problem?memberAli Khan (OKC)22 Nov '07 - 6:18 
I gave him same advice in one of my thread.
 

“If you really think that this article has nothing to do with real world scenarios/applications then why don’t you write one with real world application and examples? You can present all your ideas about exceptions, and then we will see how much appreciation you will get, and how many people will agree with you”
 

Again I will be more than happy to have positive discussion, it always gives chance to learn more. I wrote this article to share/discuss these things with others, which is an integral part of learning process, we all are learning here. However I don’t see that he wanted to discuss some thing, he probably just wanted to fight, and always believe that he is Mr. PERFECT and always right.
 
If you completely disagree with someone, you have freedom to write your own article/ideas.
 

 
Muhammad Ali Khan
System Development Analyst
Hertz Corporation

GeneralRe: Kikoz68 you have problem?memberJasonRT22 Nov '07 - 7:13 
I agree Ali Khan. Kikoz68 need to control himself. Just wanted you to know that I like your article.
 
Thanks
Jason
AnswerRe: Kikoz68 you have problem?memberRenat.R22 Nov '07 - 18:44 
Hi All
 
who is Kikoz 68 and what this is all about?
GeneralRe: Kikoz68 you have problem?memberRenat.R22 Nov '07 - 18:50 
never mind I found it
Wow those comments are huge ! Smile | :) ))))
GeneralWell...memberKikoz6819 Nov '07 - 18:30 
I've already seen some variation of this article on (I think) author's blog and somewhere else month or so ago. It feels like author wants to become a great IT guru so much that he publishes his "tips" everywhere, non-stop. But I think, instead of reading and quoting books from "gurus" like Dino Esposito, you should spend some time developing and maintaining at least a couple of real-life (read - FREAKING HIGH TRAFFIC with lots of data) applications before you dare to teach others. I'll explain:
 
1. Most of this stuff is so obvious. I mean, explaining that StringBuilder is better than concatenation is more or less like saying "I'm a son of my mom". Implement Ajax whenever possible? Yep, I agree. But UpdatePanel (read - calling page methods asynchronously) has lots of bad side-effects. I'll leave it to author to figure out what they are.
 
2. I don't want to start on Server.Transfer vs. Response.Redirect. Author clearly doesn't understand a damn thing about it. Let me just say that statement "use the overload method that accepts Boolean" is so lame. 7 years ago, when the 1st .NET version was released, all VB-lovers were screaming in every forum "I get TheadAbortException every time I use Response.Redirect!! Help MS!" MS guys and other programmers were patiently explaining that this is by design, you should catch that exception and do nothing (I'll get to exceptions later). But screams continued. So, just to educate the author: the bool in that overload, if true, will ensure that further execution will be terminated. So, if you pass "false", any code below that line will continue to execute. Let me know, dear author, if you're ok with it. Also, the ASP 2.0 DOES NOT raise this exception any more.
 
3. Using client scripts for validation? Select Tools/Options from IE menu and disable Java Script. Try now. In general, you GOT to have server-side validation. So, if you have it anyway, why bother with the client? As a side note, one piece of advise: don't use validation controls, have some simple method in C# that would validate your data. Why? Because you seem to be so cautious about your view state and they ADD a lot to view state. Also, don't tell anyone that using RegEx for validation is slow. Even if your book says so.
 
4. And finally, the favorite topic of all "wanna-be-famous-IT-guy" individuals - Exceptions.
 
First, ever though about why .NET itself relies HEAVILY on exceptions? Are you saying that framework creators are stupid?
 
Exception has two purposes: to RELIABLY terminate code execution at any moment and to bubble up the "type" of this termination. Imagine, for example, that you're authenticating your user and it's critical to know exactly why authentication failed. You spent so much typing explaining that we should separate business from presentation. What it means is that there is, for instance, a User object somewhere that has a method called Authenticate. According to you, it should return a bool. Or enum. But real authentication would probably contain several steps, each has to reliably stop execution in case of something and return the explanation why it did so. So the caller could take appropriate action(s). Wrong password? Not in domain any more? Dictionary attack? Etc.
You say that exceptions are more expensive. You bet they are. Loop 100,000 times with two statements on your machine, throw exception in one and don't throw in the other. The one with exception will take about 8 seconds, the other - just 1 second. Scared? Smile | :)
 
Now, analyze this test. 100,000 users requesting the same resource at the same moment - it's pretty much a DOS attack, i.e. totally different headache. In real life you got something like 1000 users per minute on a large site. In other words, real life doesn't really give us those max numbers. Normally GC cleans up in 0.2 to 2 seconds. Why expensive objects are dangerous? Because they take up memory. Will 1000 users per minute eat up 2-4 gigs (typical) if GC collects on time? Nope, not even close, even if ALL their requests will throw exceptions. So, what's better - to have a crappy meaningless bool returns from business layer or exact reason (type) of the exception on each unexpected situation? Read the word "exception". Something unusual. Talking about validation, how many requests will provide wrong passwords and fail validation (throw exceptions). 5 out of 1000? That's about right. So, 5 is UNUSUAL number. Usually there will be no exceptions at all. AND, no validation controls/larger view state (if we're still on validation subject)!! Because of this, you don't have to be scared that exceptions are heavier than any other approach. In my experience, exceptions perform FASTER and result in cleaner and more MANAGEABLE code than, for instance, if(Page.IsValid) stuff.
 
I would be GLAD to discuss this further, here or anywhere.
GeneralRe: Well...memberAli Khan (OKC)20 Nov '07 - 10:47 
1- “I've already seen some variation of this article on (I think) author's blog and somewhere else month or so ago. It feels like author wants to become a great IT guru so much that he publishes his "tips" everywhere, non-stop”. You think, hmm…, well your thinking is completely wrong, this is the only place I have this article or any stuff related to this topic.
 
2- “.NET itself relies HEAVILY on exceptions? Are you saying that framework creators are stupid?” Now regarding exceptions, go and read all previous threads and discussion on this topic before you say something. Also there are numerous articles written by people who designed and development .NET framework, so you think all of them are stupid and senseless. Look at these articles http://msdn2.microsoft.com/en-us/library/seyhszts.aspx http://msdn2.microsoft.com/en-us/library/ms998549.aspx#scalenetchapt06_topic22 “Exceptions are expensive. By knowing the causes of exceptions, and by writing code that avoids exceptions and that handles exceptions efficiently, you can significantly improve the performance and scalability of your application.”
 
It also states, “Exceptions add significant overhead to your application. Do not use exceptions to control logic flow, and design your code to avoid exceptions where possible.”
 
3- “In my experience, exceptions perform FASTER and result in cleaner and more MANAGEABLE code than, for instance, if(Page.IsValid) stuff”. Your view clearly contradicts with most designers’/developers’ experience, and Microsoft’s own website. Like I said, read the long discussion on Exception handling before you come up with new ideas and waste everybody’s time. By reading previous threads/discussions, you can get an idea of how many people agree with you.
 
4- People read/write Articles and books for training purpose. Articles give readers basic idea about the topic so that reader can apply those ideas in their specific situation or task at hand. This article outlines some ways/tips for performance and improvements. It doesn’t go into the details of each and every item, it will require books to explain each and everything, not everything can be fully explained in just one article. However it looks like you never went to any school or have sufficient training to understand the learning process. I am managing and designing real word applications for years, however it doesn’t mean that I will upload a real world application on this website. If you really think that this article has nothing to do with real world scenarios/applications then why don’t you write one with real world application and examples? You can present all your ideas about exceptions, and then we will see how much appreciation you will get, and how many people will agree with you.

 
Muhammad Ali Khan
System Development Analyst
Hertz Corporation

GeneralRe: Well...memberKikoz6820 Nov '07 - 18:21 
I can try to dig into my browser's history and get links to those articles for you. Two articles I've seen had the same title and were providing absolutely the same tips, point by point (StringBuilder, Server,Transfer, sprocs, exceptions, etc). I even got them from the same source - asp.net RSS feed (this one as well). I can't remember the exact text of each one, but I can assure you that they looked awfully similar to yours. Of course, you'd try to tell me that this is a common knowledge and that's why they looked the same but I seriously doubt that. Again, will try to find them. And don't get me wrong: I'm not discussing your personality or stuff like that. I really believe that you're a great guy and so on. I'm just trying to show where you're wrong. I like the tone of your reply, so I'm sorry if I got a little angry. I guess, too many everyday contacts with people who call themselves "software architects" and can't tell why a code from some sproc will perform the same as the sproc itself if run separately with the same parameter values. Fire up Profiler on some large db and check it out yourself. Result will surprise you. Then please update your article. In my opinion, your article provides very little value and mislead in many ways. This was my point. Regarding my education... Man, you REALLY don't want to go that way, believe me. I'd say only one thing: real education should enable you to think logically and analyze everything you read or see instead of just following the exact text. Now, back to the real stuff.
 
Exceptions. Please read my comments again. Did I say that exceptions are not expensive? Did I refer to any article that states the obvious? Nope. So, I'm not going to tell you "And did you read that blah.com article??" Instead, I'll tell you how to use the knowledge you got. So, should we avoid using exceptions even in flow control? No. This is where you're totally wrong and this is why I asked if you're saying that framework guys are stupid. If you were in programming long enough, you should remember the now famous "return 1 or 0 from you sprocs as indication that error occurred" wrong notion. I see the same approach in today's code from many guys. They return booleans from their methods as indication of "success" or "failure". If I ask why they wouldn't simply throw a custom exception they would look at me like I'm the baby and say "Oh, don't you know? It's a very bad practice!!" "Why?" "Because MSDN says so". I'm not kidding, I actually had this conversation 3 or 4 times for the past 2 years. As a side note, it turned out that one of those guys simply didn't know that he could create and throw his own exceptions. And, of course, his cube was full of all kinds of framed "certificates". So, are you still saying that we should expect a false from an attempt to divide by a zero? Smile | :)
 
Problem with exceptions is a logical one. New guys that want to become programmers would read your article, plus MSDN documentation and think "Ok, exceptions are bad, every one who uses them is a dork". Documentation states facts, as it should, but your article is supposed to explain documentation. It should say "Yes, exceptions are expensive, so don't throw them left and right just because you can. But you SHOULD use them if your code is potentially in danger of unpredictability." You seem to miss or ignore my main point: exception is something unexpected, unusual, something that by its nature will not be happening in 50% of all calls. I was serious with the 5/1000 ratio. Books love to illustrate the "pure evil" of exceptions with data validation example. So, I took that example as well. The perfect example of data validation is a user login form in some web application, so let's discuss that scenario:
 
In my login form I'd need to know if login failed. If yes, I'd need to know why. Because my app stores some valuable user's info, I expect all sorts of attacks and would like to take separate actions depending on the type of login failure. The points of interest here are: is this our previous employee that got fired yesterday and tries to login to screw something up? Is this a simple password mistype? Is this a password guessing attempt? Is this db failure? Bad code? Totally unknown error?
 
The actions I'm going to perform: in case of employee I'd like to record this and refer him to the "Your last paycheck is canceled" page; in case of password mistype I'd like to show some "Please check your entries" message; in case of password guessing I need to programmaticaly block IP of the request for 30 minutes, even if it'd block user's entire local subnet; in case of db or total failure I need to log this to our central repository, together with stack and exception type, for further investigation and redirect the user to "Oops, sorry" page. And, of course, as you suggested, I got a User object that is common for multiple projects. It's declared in a separate assembly and inherits from the IUser interface which has a layout common for all users, customers and anybody who might have access to any of our apps. To be able to handle all of this I have 2 ways: create a custom exception for each case or create just one exception and have a public enum member in it that would list all those things. I'd choose the second one. Now, while dragging user's request through my login code, I check for all those things and throw that custom exception with correspondent enum member in case of match. In my caller code (wherever it is) I catch that type of exception (Only! All other exceptions should be handled by your global.asax or some http module), switch through emun members to see which one I got this time and actually perform a necessary action, knowing that the user is still not logged in no matter what. Note (and this is important) that any new guy on our team would not be able to unknowingly screw this up simply because he'll get an exception on his dev machine if something that he coded doesn't work as was planned by me.
 
To finalize: if you app tries to handle all this without exceptions then I'd say that your app worth precisely zero in terms of manageability and reliability. In light of all this, do I care if login failure (read - data validation) would actually be a bit slower and would take 20kb (oh, my!!) more memory?
GeneralRe: Well...memberAli Khan (OKC)21 Nov '07 - 4:39 

“Did I say that exceptions are not expensive?”
 
If you agree that exceptions are expensive then what are you arguing about? This article emphasizes writing code that avoids exceptions and that handles exceptions efficiently because exceptions are expensive. It’s just a common sense thing, if you have it, why would you raise an exception when you can easily handle it.
 
I don’t understand what your point is, what are you trying to prove here?

Did this article say “Not to Handle Exceptions” at all? Where it says that?
 
“If you app tries to handle all this without exceptions then I'd say that your app worth precisely zero in terms of manageability and reliability”
 
I never said to handle everything without exceptions. As you agreed that exceptions are expensive, this article only suggests Not raising exceptions when you can easily avoid them.
 

 
“I can try to dig into my browser's history and get links to those articles for you”
 
Good luck. I clearly told that code project is the only place I have this article or any stuff related to this topic. I just don’t understand one thing, why you think that I will lie about it? There is no reason for me to deny, if I posted same article on other websites. The only reason you won’t accept because you don’t want to acknowledge your false ideas.
 
How can you argue about other technical things when you are not even ready to understand or accept your mistakes? You just want to impose your ideas on others and believe that what you think is right, everyone else is wrong. This website is for education and training, there is no way you can acquire education or learn new things if you are not ready to understand others.
 
I don’t want to spend rest of my life to explain same things over and over. People who know the value of professionalism, ethics, corporate culture, training and education don’t waste their time in any unhealthy conversation.

 

 
Muhammad Ali Khan
System Development Analyst
Hertz Corporation

GeneralRe: Well...memberKikoz6821 Nov '07 - 16:56 
"If you agree that exceptions are expensive then what are you arguing about". Did you actually read what people say about your stuff? Smile | :) I'm arguing about the fact that there are situations (and PLENTY OF THEM) when, even though exceptions have high priority of execution and can reserve some memory for a very short period of time, you should not take it as an iron rule because advantages they provide can be FAR greater than disadvantages. I even described one of those situations but you ignored it.
 
"this article only suggests Not raising exceptions when you can easily avoid them". Excuse me? "Do not rely on exceptions in your code and write code that avoids exceptions." Can you translate this into anything other than "don't use exceptions at all"? This is what actually forced me to post my initial comment. I've seen silly "tips" before but never with such an aplomb...
 
"why would you raise an exception when you can easily handle it." And you were questioning my education? These are 2 totally different things - raising an exception and handling it.
 
"I don’t understand what your point is". Yep, that's exactly the problem. See below, please.
 
"Your view clearly contradicts with most designers’/developers’ experience, and Microsoft’s own website" (this is a quote from your earlier comment).
 
Here is a shot of one fatal and ugly error I took not so long ago on "Microsoft's own website": http://64.20.34.90.com/error.jpg
Note that this is NOT some "non-important" site, this is The MSDN you refer to. Let me explain the image in details:
 
This is not browser's own default error page which it displays when resource is inaccessible (crap happens sometimes). It's the famous "red-and-yellow", solid indication that framework is up and running on that particular IIS and there is NO error handling WHATSOEVER. Not even a reference to a default error page in web.config. Such a lame. I'm not even going to discuss the error itself which shows the level of "experience" of all those "developers" you're talking about (no redundant maintenance service on the site of such importance when you have objects that expire??). You were referring to this site (and, obviously) its creators as a final judgment, correct? Notice, btw, that this is related to exceptions as well.
 
Here is another one: I was stupid enough to attend one of those MS "training seminars" for former Front Page users (you were referring to them as a good source of knowledge). We were supposed to get info on all new stuff in .NET 2.0. The guy on the stage was a full time MS employee. Introduction paper said that he was one of the top MS programmers in US Southeast (or something like that). Well, somehow we got into a discussion on page events and the guy was telling us (with also a great deal of aplomb - MS Programmer!) that it's simply impossible to cancel a post back on the client if the button was declared as a web control. I gave him a simple line (this.thatButton.Attributes["onclick"] = "return false;";). Amazingly, he was trying to convince me that this line will not work. I left that conference and never wasted my time on stuff like this ever since. It happened in MS building at Lakewood Pkwy, Roswell, GA 30076 (if you need details).
 
What I'm saying is that you should not blindly trust anything that comes from big names, even if this is MS. Every one should analyze documentation of objects of interest and think why sometimes things are not that straight forward as they appear. Ms is a huge organization, with all typical side effects. In general, I found that MS has only 3 teams that deserve a real unconditional respect for what they do: guys who develop C# compiler, guys who rule the Office development and SqlServer team. All other teams there that I'm aware of are very questionable in terms of their ability to develop a solid product from the ground up. Take the ASP.NET 2.0, for example. In my opinion, guys who came up with the idea of "web site project" (those APP_ folders and stuff) need to be fired yesterday. Programmers complained so much that MS had to release web application project, effectively rolling back the entire APP_ effort. Read about it here: http://west-wind.com/weblog/posts/5601.aspx
 
Also, I'm curious: why don't you answer my other questions about the rest of your "tips"? Common, have some guts!
 
I gave you an example of how I would handle certain situation in the context of whatever has been said previously, inviting you to give me your vision and how you would go about it. Instead, I'm getting "the value of professionalism, ethics, corporate culture". Corporate culture is of particular interest for me here. I bet you have a BlackBerry, jeans are a big "no no" in your office, you attend 2-3 pointless meetings a day with 5-6 PMs and button clickers (pardon - Quality Assurance Engineers) who would go on and on on something you don't really care about. And you're totally fine with it. Or am I wrong? Smile | :)
 
In conclusion: I don't add a fancy signature to my comments. I just call myself a programmer. Wois me if you need to know whom you're talking to.
GeneralRe: Well...memberAli Khan (OKC)22 Nov '07 - 6:08 
“Kikoz68 definitely needs to go through some anger management program of some sort”
 

It’s only true about you. You are not making any sense and contradicting from your own statements. You need to go see a psychoanalyst to help you little bit with your mental state. There is no way anybody would like to have any kind of discussion with you because you are not aiming for healthy discussions. If you can’t listen to others or understand others how can you answer them or disagree with them? You are a kind of person who wants to understand/listen the way they want to, without caring about what the reality is.
 

 
“Here is a shot of one fatal and ugly error I took not so long ago on "Microsoft's own website": http://64.20.34.90.com/error.jpg”
 

See, anybody can make mistake, they are human too, and probably you too. But unfortunately you believe that everyone is wrong including MSDN/Microsoft and only you are right. You are not ready to accept that you can be mistaken too. I never said that I want to prove myself as an IT Guru, however your attitude shows that you believe that what you believe is true and everything is false. What you think, are you a God of IT or what?
 

 

"Do not rely on exceptions in your code and write code that avoids exceptions." Can you translate this into anything other than "don't use exceptions at all"?
 
Yes but only if you have brain. It clearly means, “Don’t completely depend on exceptions and write code that avoids exceptions”.
 
Some programmers believe that all they have to do is just have Try/Catch statements everywhere without caring about quality of the code, if exception occurs, let .Net handle it. The whole purpose of not depending on exceptions means write quality code, don’t completely depend on exception handling when you can write better code to avoid some exception.
 
It is better to avoid some exceptions by writing better code. If you can’t write quality code, don’t misguide others.

 
I will be more than happy to have positive discussion, it always gives chance to learn more. However look at even your 1st post/thread on this article, you started like you are angry, fought with somebody and ready to kill someone. You didn’t start this conversation to discuss some thing. I wrote this article to share/discuss these things with others, which is an integral part of learning process, we all are learning here. But your attitude, your posts don’t show that. You think you are always right, interpreting everything they way you want to understand. Trying to show that you are Mr. PERFECT. We can have actual discussion if you change your attitude, keep in mind nobody is perfect here, so stop acting like that.

 
Muhammad Ali Khan
System Development Analyst
Hertz Corporation

GeneralRe: Well...memberJasonRT22 Nov '07 - 7:10 
I agree with Ali Khan. Kikoz68, if you wana learn then discuss, not fight. Nobody is 100% perfect, even Microsoft Products come with bugs and errors. This article has some good information. It makes sense if you disagree with some thing, however it’s not understandable when you only make irrelevant comments.
GeneralRe: Well... [modified]memberDutchMafia4 Aug '08 - 10:32 
Oh my. This little gold nugget of a "tiff" made my day. I have to thank you both. Where's that stupid smiley face thingy...oh yeah, here it is: Laugh | :laugh:
 
modified on Friday, August 8, 2008 12:04 PM

GeneralCorrectionmemberKikoz6821 Nov '07 - 17:00 
That error image is at http://64.20.34.90/error.jpg, sorry Smile | :)
GeneralRe: CorrectionmemberGreatThinker25 Nov '07 - 1:35 
Good Photoshoping work on image Kikoz68 Poke tongue | ;-P
 
Even if the image is original, stick to this “Humans is to make Mistakes” WTF | :WTF:
 
You told you have read this article on other websites, why don’t you post the URL and confirm, people need evident not sucking words like "I forgot..", "I guess.." , "I think.." , "I lost..." etc
 
BTW, thanks Ali Khan for great article.
GeneralTranslate in PortuguesememberFabio Galante Mans18 Nov '07 - 2:47 
Hello everything well?
Can I translate this article and to write in my community's site?
 
www.aspneti.com
 
Thank you.
Fabio Galante Mans

GeneralDatareader GetDateTime errormemberLeshia21 May '07 - 3:34 
I am trying to get the value of a field from database.(select expiry_date from users) When I use the
DBReader.GetDateTime(0)- receive the following error:
System.InvalidCastException: Specified cast is not valid. at System.Data.OleDb.ColumnBinding.ValueDateTime() at System.Data.OleDb.OleDbDataReader.GetDateTime(Int32 ordinal) at Default3.Button1_Click(Object sender, EventArgs e)
 
ANY IDEAS???Cry | :((
GeneralRe: Datareader GetDateTime errormemberdavidxavier197724 Nov '07 - 22:58 
Dunno this may sound pretty corny but have u checked that the field is actually a datetime field.also though u have used DBReader.GetDateTime(0) but what is to the left is it a Datetime object or something similiarSmile | :)
Questioncan u please explain how to use datareader better with an examplememberrama charan12 Feb '07 - 3:28 
" when you use the DataReader, you can use the specialized type-specific methods to retrieve the data for better performance" --can you please explain me about this in detail
 
thanks in advance...
 

enjoy..

Generalthank u very very muchmemberrama charan12 Feb '07 - 3:18 
its of very great help to me ...i am sure my application will boost a lot in performace with it....it has given me a better insite into what i am working on....thank u once againSmile | :)
 

enjoy..

GeneralStored procs [modified]memberDanInManchester3 Jul '06 - 4:44 
Stored procedures don't necessarily offer you any significant performance gain and are not compiled as such anyway. There is a great deal of misuse of the word compile when it comes to store procs. When we talk about compilation wrt stored procedures what we actually mean is that the server has put together or 'compiled' an execution plan. This execution plan can then be reused when SQL server encounters another command that it thinks matches the plan.
 
using parameterised queries will give you very similar performance to stored procedures. The only real difference with parameterised queries is that rather than simply send the stored procedure over the wire you send the full command text but SQL server will most likely have cached the execution plan and look it up the same it would for a stored procedure.
 
One thing you should try to avoid is dynamic SQL as this makes your SQL very variable and so you will have more execution plans and potentially each request is more likely to require new execution. if you must use dynamic SQL try to parameterise it where possible.
 
Added to this using parameterised queries adds a security layer and removes the risk of SQL injection vulnerabilities.
 
I tend to favour stored procedures where otherwise my application would be forced to go back and forth between the SQL server however I try to avoid offloading business logic to the database server to acomplish this and so it is a balancing act and you usually trade one thing off against the other.
 
There are of course arguments against using parameterised queries in your application over stroed procedures but I think that is beyond the scope od the point I am making.

 
----------------------------------
Dan Bayley
www.dbnetsolutions.co.uk
 

-- modified at 10:44 Monday 3rd July, 2006
GeneralUsing Viewstate to store objects for performancememberbenoityip16 Mar '06 - 17:54 
I am using Viewtstate in a different way to boost performance
 
1. The default Viewstate sux, stoing viewtstate in the inputfield
2. Stroing large thing in viewstate sux as well coze the serilization of view state is too slow
 
I override these two deficiencies and take viewstate as an advantage to store objects, but it does have drawbacks
 
In my page, where there is a datagrid with paging on, normally, when you click page 2,3,4... you will ask the db for more information. I use viewstate to store the dataset object so that everytime when you click page 2,3,4,5,6... it does not talk to the db...
 
1. I override the default view state implementation to store the viewstate in the session
2. I change the session to InProc, THIS WILL STOP THE VIEWSTATE FROM SERLIALIZATION, so the seralization overhead is gone. I have tried to store large object in viewstate with serialization, it took ages. I cannot belive the performance boost of making the viewstate to store in session inproc.
 
the drawback is that you it does not support multi-server environment. For the memory, no need to worry, RAM is so cheap nowadays, 1 GB of ram will serve you manay many users
 
BEN BEN
Simple and Happy Person
 
-- modified at 23:56 Thursday 16th March, 2006
GeneralThanks for the feedbackmemberAli Khan (OKC)15 Mar '06 - 11:07 
I was on vacation, sorry couldn’t really participate in the discussions. Arguments regarding exceptions and use of Stored Procedures were really interesting.
 
Darren thanks for catching a typo in the article.
Overall I am quite satisfied with the feedback I got from you guys.
 
Thanks
 
Ali Khan

 
Muhammad Ali Khan
System Development Analyst
Hertz Corporation
GeneralMore resourcesmembertvidigal8 Mar '06 - 6:33 
Hello everyone,
 
I thought that it might be usefull for everyone really interested in this kind of issues.
 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/fastmanagedcode.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/highperfmanagedapps.asp
 

best regards
 
Tiago D'Herbe
Ergogeste S.I.
http://www.ergogeste.com
http://webportal.ergogeste.com

GeneralPostback'smemberDarrenKopp2 Mar '06 - 13:46 
In the part where you have
 
If Not IsPostBack Then
LoadJScripts()
End If

 
Couple of notes on this. You call a method called LoadJScripts(), which i assume loads some javascript. I would hope that in that method you would be calling statements like
 

'VB
If Not Page.IsClientScriptBlockRegistered("myscript") Then
Page.RegisterClientScriptBlock("myscript", "<script>alert('hello world!');</script>")
End If
 
// c# code
If (!Page.IsClientScriptBlockRegistered("myscript"))
{
Page.RegisterClientScriptBlock("myscript", "<script>alert('hello world!');</script>");
}

 
These become especially crucial when they are within controls that can be used multiple times on the page, or if you would like to conditionally register the scripts. It also applies a more object oriented approach to adding the scripts, rather than say, response.write statements.
 
------
Darren Kopp
GeneralCorrectionmemberDarrenKopp2 Mar '06 - 13:21 
I believe where it says
' Recommended code
If Not num = 0 Then
value = 100 / number
Else
value = 0
End If

 
What it should be is
 
' Recommended code
If Not number = 0 Then
value = 100 / number
Else
value = 0
End If

 
------
Darren Kopp
QuestionString concatenation?memberMasjj2 Mar '06 - 10:26 
There's much more to say on the string concatenation stuff, I would recommend reading the following: http://www.yoda.arachsys.com/csharp/stringbuilder.html^]
AnswerRe: String concatenation?memberronmichael18 Nov '07 - 4:16 
That's a very useful common sense article. (with an interesting link that also talks about exceptions being expensive for those obsessed with that)
 
Ron @ Byzet

GeneralInaccuraciesmemberShazam9992 Mar '06 - 7:48 
Arg. foreach is just as fast as for. Only .NET 1.0 has problems with foreach.
 
Also, exceptions are not expensive in .NET. Where are people coming up with these things?

GeneralRe: InaccuraciesmemberR. Mark2 Mar '06 - 8:43 
Exceptions have higher priority than normal operations. In other words if exception occurs, web server has to respond to that event on high priority bases, which means more work for the server. That’s why it’s recommended to avoid exceptions. I think Ali is right “If it is possible to detect in code a condition that would cause an exception, do so”.
 
Too many exceptions can be expansive. Look at this article showing Best practices for Exception handling.
 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconBestPracticesForHandlingExceptions.asp

GeneralRe: InaccuraciesmemberShazam9993 Mar '06 - 4:39 
Where in that article does it state that exceptions are expensive?
GeneralRe: InaccuraciesmemberArch4ngel22 Mar '06 - 2:40 
"If the event happens routinely, using the programmatic method to check for errors is better. In this case, if an exception occurs, the exception will take longer to handle."
 
First paragraph after the second block of code.
 
It doesn't say "expensive" but it does say that it will take longer than a simple verification.
 
You also must understand that the exception will gather all the information about WHERE the error happenned. That means showing you which method called which method. Exception must probably be using some Reflection and that is slow.
 
So... if you put that on a web server, of course it's going to slow down things when you get an exception.
 
Cheers
 
If someone says "Die mortal!", don't stay to see if he isn't.
GeneralRe: InaccuraciesmemberDarrenKopp2 Mar '06 - 13:16 
I think that it is more expensive and have heard such from other people as well. When you think about it, when you you throw an exception you stop current execution, you create a new object with data about the execution, and then you run any cleanup that is needed (garbage colleciton).
 
Architecturally speaking, you have to save all local variables, all parameters, current location, then jump to the code that handles the exception, which there is a very good chance will not be in cache, and if the program is large enough, won't be in memory, causing a need to read data from the hard drive.
 
If you are using local variables and if statements, you will find that it will execute a lot more quickly.
 
--------
Darren Kopp
GeneralRe: InaccuraciesmemberShazam9993 Mar '06 - 4:44 
> I think that it is more expensive and have heard such from other people as well.
 
You think they are more expensive? Do you have any proof?
 
> Architecturally speaking, you have to save all local variables, all parameters, current location, then jump to the code that handles the exception, which there is a very good chance will not be in cache, and if the program is large enough, won't be in memory, causing a need to read data from the hard drive.
 
What's your app doing otherwise? Don't you think during the normal course of your app running it needs to "save local variables (?), all parameters (?), and jump to code that needs to run"?
 
> If you are using local variables and if statements, you will find that it will execute a lot more quickly.
 
I will? You have proof of that? Local variables? What does that have to do with anything?
 
The "Exceptions are expensive" urban myth started back in the C++ days. And it wasn't _throwing_ the exception that was slow, it was the sheer fact that just putting in code in a try...catch block could slow your code down by an order of magnitude.

GeneralRe: InaccuraciesmemberDarrenKopp3 Mar '06 - 17:04 
Shazam999 wrote:
The "Exceptions are expensive" urban myth started back in the C++ days. And it wasn't _throwing_ the exception that was slow, it was the sheer fact that just putting in code in a try...catch block could slow your code down by an order of magnitude.

 
You are right, adding the try...catch block does not slow down the code. But handling a 0 value in the divisor by catching DivideByZeroException is more costly.
 
Shazam999 wrote:
> Architecturally speaking, you have to save all local variables, all parameters, current location, then jump to the code that handles the exception, which there is a very good chance will not be in cache, and if the program is large enough, won't be in memory, causing a need to read data from the hard drive.
 
What's your app doing otherwise? Don't you think during the normal course of your app running it needs to "save local variables (?), all parameters (?), and jump to code that needs to run"?

 
Try learning about how a computer runs before you make broad statements. Yes, your program does have to do that, that is NORMAL progression of code. However, the computer's architecture takes advantage of locality of reference to speed up the process. This means, that when your cpu goes to get an instruction from memory, it knows that the adjacent memory blocks are probably going to be used soon, so it grabs those as well. Guess what, the exception handler is not close to your code that you are running (even though it is when you are typing it). You are going to get a cache miss, most likely a memory miss, and have to go to the hard drive. Going to the hard drive, you may even see a page fault, depending on how large the program is. A simple if statement will execute numerous times faster than an exception being thrown, handling the exception, and possibly continuing on normal code progression.
 
Shazam999 wrote:
> I think that it is more expensive and have heard such from other people as well.
 
You think they are more expensive? Do you have any proof?

 
Check out this code project link[^]
 

 

 
-----
Darren Kopp
GeneralRe: InaccuraciesmemberShazam9996 Mar '06 - 11:30 
DarrenKopp wrote:
Try learning about how a computer runs before you make broad statements. Yes, your program does have to do that, that is NORMAL progression of code.

 
No, you should learn how a computer runs, and you should stop with YOUR broad statements like "Exceptions are expensive".
 
DarrenKopp wrote:
But handling a 0 value in the divisor by catching DivideByZeroException is more costly.

 
You seem to be seriously confused. First off, if you're going to divide two numbers, before you do that, you should check the input first to see if the two numbers are valid. But there may be times where that check is incomplete, and that's where the DivideByZeroException needs to be thrown.
 
In this case as well, what's the error code you'd bring back versus an exception? -1? -15? A string like "Can't divide by zero?"
 
DarrenKopp wrote:
However, the computer's architecture takes advantage of locality of reference to speed up the process. This means, that when your cpu goes to get an instruction from memory, it knows that the adjacent memory blocks are probably going to be used soon, so it grabs those as well. Guess what, the exception handler is not close to your code that you are running (even though it is when you are typing it). You are going to get a cache miss, most likely a memory miss, and have to go to the hard drive. Going to the hard drive, you may even see a page fault, depending on how large the program is. A simple if statement will execute numerous times faster than an exception being thrown, handling the exception, and possibly continuing on normal code progression.

 
First off, we are talking about an article that deals with ASP.NET, so you'd better hope that your app totally fits within available RAM, or else you're in serious trouble off the bat in terms of web server response, so I don't know why you're babbling about cache hits/misses.
 
Secondly, exceptions are just that - something really bad has happened that more often than not will require the program to stop. If I get a DatabaseNotExists exception, then there's no real point in my app going along.
 
If you're throwing exceptions like crazy, then you need some serious rethinking.
 
DarrenKopp wrote:
Check out this code project link[^]

 
So you give me a link that proves my point. Well that sure works well for your case.
 

 
-- modified at 17:31 Monday 6th March, 2006
GeneralRe: InaccuraciesmemberRobert1017 Mar '06 - 5:19 
I think it’s not really hard to understand “why too many Exceptions can be expensive”. However if someone does not believe in common sense then he can find numerous articles on Microsoft website regarding the topic. J.D. Meier, Srinath Vasireddy, Ashish Babbar, John Allen and Alex Mackman (all Microsoft ASP.NET team members) wrote article “Improving ASP.NET Performance”
 
They wrote
 
“Exceptions are expensive. By knowing the causes of exceptions, and by writing code that avoids exceptions and that handles exceptions efficiently, you can significantly improve the performance and scalability of your application.”
 
They also wrote
 
“Exceptions add significant overhead to your application. Do not use exceptions to control logic flow, and design your code to avoid exceptions where possible.”
 
Look at this and hundreds of articles on Microsoft official website before calling it an “urban myth” or “broad statement without any proof”.
 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt06.asp

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 21 Mar 2006
Article Copyright 2006 by Ali Khan (OKC)
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid