Tips And Tricks: Performance Tips and Techniques in .Net

Few Performance Tips in .Net

(will be updated regularly)

Following are few tips collated from different reading material found in Books and Internet.

1) Shortcut assignment operators

Using the shortcut assignment operators reduces the typing you need to do. They are also more efficient at runtime, because the variable needs to be evaluated only once.

commonly used shortcut assignment operators like these +=, -=, *=, /=, \=, &=,should be used.

For Eg. Use sum += value instead of sum= sum+ value. Since, this can result in lots of unnecessary work. This forces the JIT to evaluate both copies of sum, and many times this is not needed. The first statement can be optimized far better than the second, since the JIT can avoid evaluating the sum twice.

2) Exception Handling

The general rule of thumb is to put exception as close to the end user-generated event that caused the issue as possible, but still retain enough information to handle the exception as needed. For example, the structured error handler would be in the Click event procedure for the button(Submit/Save).

Another rule of thumb is to never catch an exception unless you plan to do something with it.You should not catch an exception and then simply rethrow it. That has a negative impact on performance and provides no benefit.

Throwing exceptions can be very expensive, so make sure to minimize this cost.You can use Perfmon to check the number of exceptions your application is throwing.

The run time can throw exceptions on its own! For example, Response.Redirect() throws a ThreadAbort exception. Even if you don’t explicitly throw exceptions, you may use functions that do. Make sure you check Perfmon to get the real story, and the debugger to check the source.

Bear in mind that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. Make sure that never use exceptions to control the application flow,instead check for the condition which causes the exception.

3) Keep DOM Updates to a Minimum

To do anything interesting, your code has to modify the DOM. However keep in mind that changes to the DOM are extremely expensive. Understandably, the browser has to do quite a bit of work to handle calls to the DOM API that change the content of the page. Even more surprisingly, calls to methods that do not change the page can be particularly slow, as, for example, registering listeners.
Also beware of code that iterates over a large number of DOM objects, such as code that iterates over document.all to look up a particular element, or uses document.getElementByName(). When using
those, as the size of your page grows so will the time taken by your code to execute.

4) Handling Memory Leaks

Event listeners are a major cause of memory leaks, both on Internet Explorer and Firefox, because event listeners routinely refer to other elements. The way to get around this problem is to keep track of every event listener you register and to unregister all those listeners when the user navigates away from the page, thus breaking the loop and allowing the garbage collector to clean up afterwards.

On Firefox, the Leak Monitor extension will help you detect memory leaks in your pages. When installed, as you navigate away from a page, the extension will display a pop-up with the list of leaked objects for that page. If no pop-up is displayed, it means that no memory leak was caused by that page.
You can download and install the Leak Monitor extension from

5) Cache Aggressively

There are several features and tools in ASP that you can make use of to gain performance.
Output Caching—Stores the static result of an ASP request. Specified using the directive:

Duration—Time item exists in the cache
VaryByParam—Varies cache entries by Get/Post params
VaryByHeader—Varies cache entries by Http header
VaryByCustom—Varies cache entries by browser
Override to vary by whatever you want:
Fragment Caching—When it is not possible to store an entire page (privacy, personalization, dynamic content), you can use fragment caching to store parts of it for quicker retrieval later.
a) VaryByControl—Varies the cached items by values of a control

Cache API—Provides extremely fine granularity for caching by keeping a hashtable of cached objects in memory (System.web.UI.caching). It also:
a) Includes Dependencies (key, file, time)

b) Automatically expires unused items

c) Supports Callbacks

Caching intelligently can give you excellent performance, and it’s important to think about what kind of caching you need.


Tips and Tricks :Visual Studio .Net IDE

Tips and Tricks :Visual Studio .Net IDE

A collection of tips and tricks, features, for the Visual Studio .NET IDE.

Read from the book Best Kept Secrets in Dot NET from the APress publishing house.

1. Multiple copy/pastes

Ctrl+Shift+V cycles through the clipboard ring. You can copy/cut multiple times from one area of code, then go to another area and paste them one after another.

2. Previous cursor positions

Ctrl+ - i.e. Ctrl + Hyphen. This cycles you through the code positions you visited.

Ctrl+Shift+- to navigate in the opposite direction.

3. Incremental search

To incrementally search for text as you type, first press Ctrl+i. Then type the word you want to search. Hit backspace to clear a character and enter to finish. Pressing F3 after this will work as usual, i.e. search for the next occurrence of previous search.Ctrl+Shift+i is used for Reverse Incremental Search.

4. Matching brace/comment/region/quote

Ctrl+] takes you to the matching brace. It also takes you to the matching comment, region or quote depending on what is at the cursor now.

5. Vertical block selection

Press Alt and then select the area you want with your mouse.this is very useful when you have to delete line numbers or some common unwanted text in all the lines,like for eg. Using a WITH block and removing the object name from multiple lines of the code.

6. Closing/Showing support windows

There are a bunch of necessary/useful windows in the Visual Studio IDE like Properties (F4), Solution Explorer (Ctrl+Alt+L), Output Window (Ctrl+Alt+O), Task List (Ctrl+Alt+K) etc. However, they take up a lot of space. An easy way around this is to use the auto hide feature.

Open the window you want. Right click on its title and choose Auto Hide. The window will dock in whenever your mouse is not hovering over it.

7. Track things you have to do with Task List

The Task List window (Ctrl+Alt+K) allows you to keep track of the things you have to do. Right click on the Task List window and choose Show Tasks|All to see a list of tasks. Ctrl+Shift+F12 to cycle through your list of tasks.

By default, comments marked with a TODO will appear in the task list.

8. Edit Task List Comment Tokens

You can add your own set of comment tokens (like the TODO comment token). Goto Tools|Options|Environment|Task List|Comment Tokens and make your changes. You can change the priority appearance of each comment token too.

9. Add Task List Shortcut

Add a shortcut to the task list with Ctrl+K, Ctrl+H. This will add the current line to the task list.

10. Auto-complete (Almost everyone knows this one)

Press Ctrl+Space or Alt+RightArrowto auto-complete the word. Intellisense suggestions may pop up a window if there is more than one possibility.

11. Intellisense suggestions window

Press Ctrl+Shift+Space to bring up the intellisense suggestions window. When giving parameters for functions, I often need to escape the suggestions window to check another part of code. To bring it back, I used to delete a comma and then type it again; but this is easier.

12. Line numbering

Tools|Options|Text Editor|All Languages|General|Line numbers.

If you want to set this option for only one language, then choose the appropriate language instead of All Languages.


Bookmarks are available through Edit|Bookmarks. Bookmarks allow you to mark places in your code that you would want to come back to.

  • Create/Remove Bookmark – Ctrl+K, Ctrl+K
  • Move to next bookmark – Ctrl+K, Ctrl+N
  • Move to previous bookmark – Ctrl+K, Ctrl+P
  • Clear all bookmarks – Ctrl+K, Ctrl+L

14. Code Formatting

  • Auto-format selection – Ctrl+K, Ctrl+F
  • Convert to lower case – Ctrl+U
  • Convert to upper case – Ctrl+Shift+U
  • Comment selection – Ctrl+K, Ctrl+C
  • Uncomment selection – Ctrl+K, Ctrl+U

15. Outlining

I like this feature that allows me to hide code that is irrelevant to what I’m currently working on.

  • Fold/Unfold the current code block – Ctrl+M, Ctrl+M
  • Unfold all – Ctrl+M, Ctrl+L
  • Stop outlining – Ctrl+M, Ctrl+P
  • Fold all – Ctrl+M, Ctrl+O

16. Build and Debug

  • Build – Ctrl+Shift+B
  • Run – Ctrl+F5
  • Debug – F5

17. Wrapping Code

If you have long code lines, you’ll find that you do a lot of horizontal scrolling to view the entire line. As an alternative, you can wrap the code lines so you can view the code without needing to scroll.The easiest way to toggle word wrapping is by pressing Ctrl+R and then Ctrl+R again or by selecting Edit –> Advanced –> Word Wrap from the menu. When word wrapping is turned on, the horizontal scroll bar is removed and any lines of code that exceed the width of the code window will automatically wrap to the next line. This wrapping does not require any additional line-continuation characters (for VB), nor does it affect how the code is compiled.

Volta and GWT continues…… (II part)

The Volta features,

The most important aspect of any microsoft product is the familiarity, that what thy bank on the user-friendliness, that comes from the familiar usage of the keyboard keys, tools and techniques.Across all products it literally the same.

Same is the case of Volta too, but here the familiarity is the language, i.e the .Net languages, The Volta application is structured like a WinForms application, so is like bread n butter to most of the developers.

Similar to GWT , Volta also has extended support for creation of custom controls along with the basic set provided, which most of the developers developing custom controls in .Net windows and web applications.

Biggest change micrsoft have got into volta is that it the MSIL is recompiled to the target environment, In essence Volta is a recompiler. Volta works on MSIL rather than on a textual source language. Volta rewrites MSIL into any number of target languages, including, JavaScript and MSIL itself. This helps us to delay permanent decisions about architecture, target environment until after our code is basically instead of worrying about the architecture the developer can concentrate more on the problem rather than the material things around.

(Following Excerpt From Microsoft labs website)

In summary, Volta confers flexibility in the architecture dimension through:

  • Language-independence. Write Volta code in any language that compiles into MSIL. For example, C#, VB, IronPython, etc.
  • Leverage the entire .NET toolchain. Use libraries; the IDE, Intellisense, auto-complete, snippets; FxCop; profiler; class browser; ILDASM; and so on.
  • Low entry barrier. Reduce your learning burden; use “only the languages in the room.”
  • Brown-field applicability. Volta-enable existing applications for the cloud.
  • Beyond 2 tiers. Refactor to as many tiers as you need using exactly the same mechanisms recursively applied.
  • Deep embedding of CLR semantics. Preserve exact CLR semantics across platforms.
  • Cross-browser support. Use one programming model across browsers.
  • Complete orthogonality with refactoring. Mix and match refactoring and retargeting.
  • Ajax-ready. Write Ajax patterns and idioms in familiar .NET languages.
  • Cross-browser support. Write the same code for Internet Explorer and Firefox.
  • Debugging transparency. Debug code with a specific browser.
  • Leverage browser-specific features. Where needed, access features unique to each browser.
  • Visual-Studio integration. Enjoy seamless integration with the IDE.

Pretty similar features to GWT .

Lets see in future which of them fare better, its again the fight of the open source and the proprietary software.

The Google Vs Microsoft fight can reap rich benefits for developer like you and me and also the world which is plugged in to the internet 24/7 😛

Thats it for today,till then bye and have a great day ahead.

– Deepak.

Volta and GWT continues……

Lets start with the GWT features…

GWT user interface classes are similar to those in existing UI frameworks such as Swing and SWT(Standard Widget Toolkit) except that the widgets are rendered using dynamically-created HTML rather than pixel-oriented graphics.

GWT applications construct user interfaces using widgets that are contained within panels. Examples of widgets include Button, TextBox, and Tree.

These widgets work the same way across all the browser (cross-browser ability), due to this there is no need to write separate functionality for each of the browsers.Custom made widgets can also be developed along with the basic set provided by the toolkit.

The addition of widgets , the events etc are pretty similar to coding in Java.

Visual styles can be applied to widgets using Cascading Style Sheets (CSS).

for more details about different widget refer to Google Developer Guide

In production environment, the code is compiled to JavaScript.But at development time it runs in the Java virtual machine. That means when the code performs actions like handling a mouse event, we get a full-featured Java debugging, with exceptions and the advanced debugging features of IDEs like Eclipse.

Cross-Browser compatibility,GWT applications automatically support IE, Firefox, Mozilla, Safari, and Opera with no browser detection or special-casing within your code in most cases.

GWT’s direct integration with JUnit lets you unit test both in a debugger and in a browser.

Completely Open Source,All of the code for GWT is available under the Apache 2.0 license.

Benefits of GWT in building the AJAX applications

  • You can use all of your favorite Java development tools (Eclipse, IntelliJ, JProfiler, JUnit) for AJAX development.
  • Static type checking in the Java language boosts productivity while reducing errors.
  • Common JavaScript errors (typos, type mismatches) are easily caught at compile time rather than by users at runtime.
  • Code prompting/completion is widely available.
  • Automated Java refactoring is pretty snazzy these days.
  • Java-based OO designs are easier to communicate and understand, thus making your AJAX code base more comprehensible with less documentation.

Volta features in the next blog.. till then bye..

have a great day ahead 🙂

– Deepak

Microsoft versus Google Again…

ya trying to write my first blog……

Microsoft has come up with something called “Volta”… now whats Volta and why its versus Google.. the answer is its a kinda product placed against the toolkit by google i.e. Google Web Toolkit fairly known as the GWT.

I have just started to explore what these two product mean..the similarities the differences, may be i could note down a few here…i am not great at writing though 🙂

Lets start with what is Volta and what is GWT

The Volta technology is a “Experimental” toolset that help to expand the known and quite familiar .Net understanding and implementations in to multi-tier web applications.

It is like designing and building the complete Ship as a single structure using known tools and appliances then specializing the sections.

i.e building the app with the knopwn .net client app., then assign the portions of the application to run on the server and the client tiers or any other middle tiers as we move forward in the development process.

The compiler creates cross-browser JavaScript for the client tier, web services for the server tier, and communication, serialization, synchronization, security, and other boilerplate code to tie the tiers together.

Developers can target either web browsers or the CLR as clients and Volta handles the complexities of tier-splitting for you. Volta comprises tools such as end-to-end profiling to make architectural refactoring and optimization simple and quick. In effect, Volta offers a best-effort experience in multiple environments without any changes to the application.

The programmer can still debug and test the application, much as if it were still on the client-tier, because Volta’s tier-splitting is deeply integrated with Visual Studio 2008 and the .NET Framework 3.5. In summary, Volta extends the .NET platform to distributed software+services applications, by using existing and familiar libraries, languages, tools, and techniques. (excerpt from the microsoft labs volta overview)

Once again. Remember its an “experimental” developer toolSET (nbt toolkit :P)

Now whats GWT ..?? (Excerpt from the GWT Overview)

Google Web Toolkit (GWT) is an open source Java development framework that lets you escape the matrix of technologies that make writing AJAX applications so difficult and error prone. With GWT, you can develop and debug AJAX applications in the Java language using the Java development tools of your choice. When you deploy your application to production, the GWT compiler translates your Java application to browser-compliant JavaScript and HTML.

Here’s the GWT development cycle:

  1. Use your favorite Java IDE to write and debug an application in the Java language, using as many (or as few) GWT libraries as you find useful.
  2. Use GWT’s Java-to-JavaScript compiler to distill your application into a set of JavaScript and HTML files that you can serve with any web server.
  3. Confirm that your application works in each browser that you want to support, which usually takes no additional work

Few points what i could understand from the above overview (correct me if i am wrong)

i) Both targeting the huge arena called the World Wide Web.. i.e. the web technologies

ii) The buzzword “Cross-Browser” support with minimum fuss.

iii) Writing the code in much more of a known territory and then expanding over.

iv) Re-usablility of code, libraries, known patterns and techniques

Both the toolSET and toolKIT are in a very nascent stage.

The goal of these is to simplify the tasks (designing, building, deploying, testing, and debugging ) of a normal developer required for the distributed, multi-tier applications which are difficult to test and debug.

Makes life easier for developers as they don’t have to learn a NEW language , they can live with what they know fairly well i.e. Java or .Net and continue to grow in the extremely fast paced web development.This can help a great deal as the developer can focus on the core development rather than worrying about the New Language or a New technology.


Lets see how Volta Works

V olta first calls on the existing .NET language compilers to generate MSIL from source code . Then, based on declarative attribute annotations, Volta rewrites the generated MSIL and splits a single-tiered assembly to run across multiple tiers.

Based on the same declarative attributes and static code analysis, Volta optionally inserts instrumentation hooks into the code. This allows end-to-end, debugging, testing, performance profiling and security profiling of multi-tier web applications.

When no version of the CLR is available on the client, Volta may translate MSIL into semantically-equivalent Javascript code that can be executed in the browser. In effect, Volta offers a best-effort experience in the browser without any changes to the application.

And now how GWT works..?

The heart of GWT is a compiler that converts Java source into JavaScript, transforming your working Java application into an equivalent JavaScript application. Generally speaking,

  1. If your GWT application compiles and runs in Hosted Mode as you expect
  2. And GWT compiles your application into JavaScript output without complaint,
  3. Then your application will work the same way in a web browser as it did in hosted mode.

The GWT compiler supports the vast majority of the Java language itself. The GWT runtime library emulates a relevant subset of the Java runtime library.

Hosted mode In hosted mode, your application is run as Java bytecode within the Java Virtual Machine (JVM). You will typically spend most of your development time in hosted mode because running in the JVM means you can take advantage of Java’s debugging facilities and remain within an IDE like Eclipse.

Web mode – In web mode, your application is run as pure JavaScript and HTML, compiled from your original Java source code with the GWT Java-to-JavaScript compiler. When you deploy your GWT applications to production, you deploy this JavaScript and HTML to your web servers, so end users will only see the web mode version of your application.

Pretty similar huh?

A thing that stands out for GWT is its Completely Open Source.

All of the code for GWT is available under the Apache 2.0 license. If you are interested in contributing, please visit Making GWT Better.

I think enough of it for today, will be posting my understandings as i understand both of the techs.

The above blog is made up of two labs MS Labs and Google Labs

(content also copied from their sites posted below :P)

Enjoy reading from there too… me too reading from there 🙂

Have a great day ahead.

– Deepak