Sunday, May 17, 2009

Optimize C# Code... 2

Optimize C# Code... 2

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Use of the operator ?: and ??

The conditional operator ?: returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form:

condition ? first_expression : second_expression;

If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.


if(i == 0) str = "Zero" else str = "Non Zero";


using the conditional operator, it will be as follow:


string str = x == 0 ? "Zero" : "Non Zero";


The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types.
It returns the left-hand operand if it is not null; otherwise it returns the right operand.


if (string.IsNullOrEmpty(str))
newstr = "i don't wanna be null"
else
newstr = str;



using the conditional operator, it will be as follow:


string newstr = str ?? "i don't wanna be null";


2. TryParse and Parse
The big difference between TryParse and Parse, is that the first one will return a boolean value, indicating if the conversion was successfull or not, and the second one will give you an exception if the convertion was not possible.


string AreYouADeveloper = "true"

if (bool.TryParse(AreYouADeveloper, out boolValue))
{
MessageBox.Show("welcome developer guy")
}
else
{
MessageBox.Show("You Are Not a Developer")
}



3. Exceptions cause performance to suffer significantly
Since exceptions cause performance to suffer significantly, you should never use them as a way to control normal program flow, so the best way is to write code that avoids exceptions. 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.

4. .Net System.Diagnostics.DebuggerStepThrough Attribute
Sometimes when you are running your code in debug mode, you don't want to stop in some methods, maybe because you already know that this method will always return what you want, because is not so important for the job you have in hands, or some other reasons... That's where the DebuggerStepThrough comes in. The compiler will add the necessary metadata preventing the debugger to step into the method. Even if you have this attribute defined, you can stop in, if you define a breakpoint there.


public string Name
{
[System.Diagnostics.DebuggerStepThrough]
get { return name; }
}

Monday, May 11, 2009

Backup / Restore blogger blog

The world of blogging is growing up very fast. You have a lot to choose when you want to start writing your own blog.
I choose Blogger because it's simple, easy to work and via my gmail account.
But if you want to backup your blog, there is no official tool to do it.

I found on Codeplex a tool to backup a blog, very easy to use and very usefull.

The name of the tool is Blogger Backup.

Check it out now!




Monday, May 4, 2009

Optimize C# Code... 1

Optimize C# Code... 1

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Knowing when to use StringBuilder
You must have heard before that a StringBuilder object is much faster at appending strings together than normal string types.
The thing is StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.
However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.
Simply choosing correctly between StringBuilder objects and string types you can optimize your code.

2. Comparing Non-Case-Sensitive Strings
In an application sometimes it is necessary to compare two string variables, ignoring the cases. The tempting and traditionally approach is to convert both strings to all lower case or all upper case and then compare them, like such:

str1.ToLower() == str2.ToLower()

However repetitively calling the function ToLower() is a bottleneck in performace. By instead using the built-in string.Compare() function you can increase the speed of your applications.
To check if two strings are equal ignoring case would look like this:

string.Compare(str1, str2, true) == 0 //Ignoring cases

The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty
This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:

if (str == "")

with:

if (str == string.Empty)

This is simply better programming practice and has no negative impact on performance.
Note, there is a popular practice that checking a string's length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>
ArrayList are useful when storing multiple types of objects within the same list. However if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.
Take the following ArrayList:

ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;

Notice it only contains intergers. Using the List<> class is a lot better. To convert it to a typed List, only the variable types need to be changed:

List intList = new List();
intList.add(10)
return intList[0] + 20;

There is no need to cast types with List<>. The performance increase can be especially significant with primitive data types like integers.

5. Use && and || operators
When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).
If statements that use & and | must check every part of the statement and then apply the "and" or "or". On the other hand, && and || go thourgh the statements one at a time and stop as soon as the condition has either been met or not met.
Executing less code is always a performace benefit but it also can avoid run-time errors, consider the following C# code:

if (object1 != null && object1.runMethod())

If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch
Try-Catch statements are meant to catch exceptions that are beyond the programmers control, such as connecting to the web or a device for example. Using a try statement to keep code "simple" instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions
C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion

From Visual C# Kicks