Performance Best Practices - Part 2 - Server Side


Published on

This time the focus shifts to the server side. The simple agenda for the 2 hrs session includes - Performance Best practices to adhere to when working with server side code in .NET, C#, MVC, LINQ and Entity Framework.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Performance Best Practices - Part 2 - Server Side

  1. 1. Performance Best Practices – Part 2 – Server Side [.NET, C#, MVC, LINQ, EF] Presenter: Sathyan, Mindfire Solutions Date: 08th Oct 2013
  2. 2.    Use Using statements wherever possible Avoid Exceptions –NULL reference exception - Be safe! Make Use of TryParse Etc! Also even when you use TryParse remember that it will handle just an ArgumentException and Not all types! After avoiding as much as possible, expect & handle Exceptions, even though there are some who argue that Exception Handling is costly, No, it is not an option not to have it at all! Presenter: Sathyan, Mindfire Solutions
  3. 3.      control application flow based on exceptions? It is just not try – catch; let us not forget finally! Also remember try-finally It is better not to throw! When you catch an exception, creating an object and then throwing will alter stacktrace, not a best thing to have when we want to track and shoot down exceptions Never suppress exceptions – Empty Catch blocks; they serve NO purpose! Presenter: Sathyan, Mindfire Solutions
  4. 4.    Dispose objects, Yes, this is indeed a debatable point but let us be safer than sorry! It is always safer to call Close or Dispose for supported objects rather than not doing it; implement IDisposable! Acquire late, release early Declare as close as to usage as possible – don’t do this when you have a really huge loop, better to declare outside! Presenter: Sathyan, Mindfire Solutions
  5. 5.     If we need to get 10 items, it is always preferable to get all 10 together rather than connecting/fetching 10 times! Reuse code as much as possible. DRY! Don’t Repeat Yourself! Just Do It Avoid locks & synchronization as much as possible, use only when it is justified and when you are a Master of the Game Consider using Task Factory – Parallel processing for heavy processing loops – Presenter: Sathyan, Mindfire Solutions
  6. 6.    Boxing (and unboxing) is best left to stages and competitions, avoid as much as possible. This is where Generics help, before Generics we were left with only Objects, which would make the CLR to box unbox internally so many thousands of times in each application, each day! Firing queries inside loop is bad and should be avoided, as much as possible get all necessary data in the outer query Use String Builder over Concat when you need to append more than 6 or 7 string instances Presenter: Sathyan, Mindfire Solutions
  7. 7.    Be aware that comparing unconstrained type parameter values against Null is extremely slow for nullable value types Always return only what is necessary With fields of type derived from MarshalByRefObject, the performance is particularly bad because the CLR really ends up calling methods to perform the field access. Presenter: Sathyan, Mindfire Solutions
  8. 8.    We all know that reflection is bad, so please use it only it is absolutely needed like creation of all new dynamic runtime forms Etc. ASP.NET DataBinder.Eval is to be avoided – it uses reflection internally Virtual methods are great but come with a performance overload, so seal your classes whenever possible and when you don’t mean to inherit them anymore! Presenter: Sathyan, Mindfire Solutions
  9. 9.   Stack<T> for a LIFO; Queue<T> for a FIFO; List<T> for random access with zero based indexing; if no duplicates in the collection, always use HashSet<T> - that is the fastest of the lot; Dictionary<TKey,List<TValue>> over List <KeyValuePair<TKey,TValue>> for O-M - Lookup speed will be much faster and client code will be less clumsy. Link: Presenter: Sathyan, Mindfire Solutions
  10. 10.     Prefer LINQ Standard Query Operator Where() over Contains(), Exists(), or Find() methods to check whether a value is present in a List<T> instance. Use the OrderBy() or the OrderByDescending() method to sort any IEnumerable<T> Avoid using of AsEnumerable() as it processes on memory rather than on DB. Prefer Query Syntax over looping! Looping is heavy in any programming language! Presenter: Sathyan, Mindfire Solutions
  11. 11.        Session State View State – Disable/Store In Server Example Shown Round Trips Pagination Pooling Choose Your controls Debug in Live Code? Trace? Presenter: Sathyan, Mindfire Solutions
  12. 12.        Cache – Output Cache(Browser, kernel, Proxy) Control caching Per-Request Caching – HttpContext Fixed Connection string and a consistent service account Pool! Return Only what you need Exception Handling Presenter: Sathyan, Mindfire Solutions
  13. 13.         Heap Objects – CLR Profiler OrdinalIgnoreCase – String Compare Multiple Inserts at one Go Grids Client side applications Log? startMode – IIS – First Request – precompile .NET 4.5 AysnchConstructs Presenter: Sathyan, Mindfire Solutions
  14. 14.       Parameterized Calls Page.IsPostBack Loops Client Side Validations Asynch Calls Refactor Presenter: Sathyan, Mindfire Solutions
  15. 15.        ADO - DataReader Vs DataSet Multiple ResultSets Reader.NextResult() Command Type Execute Scalar Execute NonQuery DataReader CommandBehavior.CloseConnection DataReader - SchemaOnly DataSets – PrimaryKeys, Rows.Find Presenter: Sathyan, Mindfire Solutions
  16. 16.      Set Sessionstate to read only when you do not write anything on services, controllers, Even WCF Etc. Stateless controllers Use the AjaxRender Helper class [which is a rendering engine] wherever applicable to allow Asynch loading Synchronous and Asynchronous pipelines in MVC and make sure to use the appropriate one at appropriate place Use Html.ActionLink - Avoid Broken Links Presenter: Sathyan, Mindfire Solutions
  17. 17.  Use only the View Engines that you need protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); }    Uninstall URL Rewrite if you don’t use it Avoid passing null models to views Remove unused HTTP Modules  Presenter: Sathyan, Mindfire Solutions
  18. 18.    Explicitly tell EF the type of the expected result wherever possible to avoid pulling all possible derived types When you want to retrieve a single entity using entity key can be more efficient than using WHERE clause [use of GetObjectByKey() method] To efficiently retrieve entities that will only display and not update, use the MergeOption.NoTracking merge option Presenter: Sathyan, Mindfire Solutions
  19. 19.    Avoid “let” in your queries as much as possible Consider using Compiled Queries – CompileQuery.Compile() [note that this decreases readability] – EF5 – Auto Compiled ALWAYS see the actual SQL generated – you will have many surprises here, you can use LINQPad or MiniProfiler-EF or simply the trace form SQL – Presenter: Sathyan, Mindfire Solutions
  20. 20.      I would personally advise SPs for anything complex [though opinion is divided here] Limit the scope of the ObjectContext Once again, get ONLY the records that you need! SQL doesn’t care about CASE so do not bother about using ToLower() Etc in your LINQtoSQL “for” is the fastest way of iterating over a collection, foreach is a little slower, and LINQ queries are slowest Presenter: Sathyan, Mindfire Solutions
  21. 21.      Glimpse Mini Profiler ANTS NewRelic NDepend Presenter: Sathyan, Mindfire Solutions