Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

Wednesday, December 7, 2011

Ways To Optimize C# Code

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<int> intList = new List<int>();

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 usingif 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.

Conclusion

As you can see these are very simple C# code optimizations and yet they can have a powerful impact on the performance of your application. To test out the optimizations, try out the free Optimizing Utility.

Profiling

An important concept when it comes to increasing the speed and efficiency of you C# code, is code profiling. A good profiler can not only let you know about the speed bottlenecks in your applications, but it can also help you with memory management. The best .Net profiler is probably RedGates ANTS Profiler. They have a free trial at their homepage you can download before purchasing the full product.

Source From : http://www.vcskicks.com/optimize_csharp_code.php 

C sharp Sample Programs


Linear Search Program

using System;
class linSearch
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Enter number of elements you want to hold in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-------------------------");
Console.WriteLine("\n Enter array elements \n");
for(int i=0;i<x;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.WriteLine("-------------------------");
Console.WriteLine("Enter Search element\n");
string s3=Console.ReadLine();
int x2=Int32.Parse(s3);
for(int i=0;i<x;i++)
{
if(a[i]==x2)
{
Console.WriteLine("-------------------------");
Console.WriteLine("Search successful");
Console.WriteLine("Element {0} found at location {1}\n",x2,i+1);
return;
}
}
Console.WriteLine("Search unsuccessful");
}
}

Binary Search Program

using System;
class binSearch
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" Enter array elements ");
Console.WriteLine("-----------------------");
for(int i=0;i<x;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.WriteLine("--------------------");
Console.WriteLine("Enter Search element");
Console.WriteLine("--------------------");
string s3=Console.ReadLine();
int x2=Int32.Parse(s3);
int low=0;
int high=x-1;
while(low<=high)
{
int mid=(low+high)/2;
if(x2<a[mid])
high=mid-1;
else if(x2>a[mid])
low=mid+1;
else if(x2==a[mid])
{
Console.WriteLine("-----------------");
Console.WriteLine("Search successful");
Console.WriteLine("-----------------");
Console.WriteLine("Element {0} found at location {1}\n",x2,mid+1);
return;
}
}
Console.WriteLine("Search unsuccessful");
}
}

Selection Sort Program

using System;
class selectionSort
{
public static void Main()
{
int[] a= new int[100];
int min,pass,i;
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" array elements ");
Console.WriteLine("-----------------------");
for(int j=0;j<x;j++)
{
string s1=Console.ReadLine();
a[j]=Int32.Parse(s1);
}
for(pass=0;pass<x-1;pass++)
{
min=pass;
for(i=pass+1;i<x;i++)
{
if(a[min]>a[i])
min=i;
}
if( min!=pass)
{
int k=a[pass];
a[pass]=a[min];
a[min]=k;
}
}
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Sorted elements of an array are(selection sort)");
for (int j=0;j<x;j++)
Console.WriteLine(a[j]);
}
}

Bubble Sort Program

using System;
class bubbleSort
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" array elements ");
Console.WriteLine("-----------------------");
for(int j=0;j<x;j++)
{
string s1=Console.ReadLine();
a[j]=Int32.Parse(s1);
}
int limit= x-1;
for(int pass=0;pass<x-1;pass++)
{
for(int j=0;j<limit-pass;j++)
{
if(a[j]>a[j+1])
{
int k=a[j];
a[j]=a[j+1];
a[j+1]=k;
}
Console.WriteLine("------------------------------------------------");
Console.WriteLine("Sorted elements of an array are(buble sort)");
for (int j=0;j<x;j++)
Console.WriteLine(a[j]);
}
}

Finding Largest and Smallest Number

using System;
class Test
{
public static void Main()
{
int n;
float large,small;
int[] a = new int[50];
Console.WriteLine("Enter the size of Array");
string s= Console.ReadLine();
n=Int32.Parse(s);
Console.WriteLine("Enter the array elements");
for(int i=0;i<n;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.Write("");
large =a[0];
small= a[0];
for(int i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
else if(a[i]<small)
small=a[i];
}
Console.WriteLine("Largest element in the array is {0}",large);
Console.WriteLine("Smallest element in the array is {0}",small);
}
}

Fibonacci Series

using System;
class FS
{
public static void Main()
{
int n;
Console.WriteLine("Number of terms to be generated ?");
string s=Console.ReadLine();
n=Int32.Parse(s);
Console.WriteLine("*******************************");
Console.WriteLine("Fibonacci seqence upto {0}",n);
Console.WriteLine("*******************************");
test1.generateFib(n);
}
}
class generateFib
{
static int f1=0;
static int f2=1;
public static void fib(int n)
{
int temp;
if(n<2)
{
f1=0;
f2=1;
}
else
{
fib(n-1);
temp=f2;
f2=f1+f2;
f1=temp;
}
Console.WriteLine(f1);
}
}

Palindrome Program

using System;
class palindrome
{
public static void Main()
{
int n,num,digit,sum=0,rev=0;
string s;
Console.WriteLine("*******************");
Console.WriteLine("Please enter a number");
Console.WriteLine("*******************");
s=Console.ReadLine();
num=Int32.Parse(s);
n=num;
do
{
digit=num%10;
sum+=digit;
rev=rev*10+digit;
num/=10;
}while(num!=0);
Console.WriteLine("*******************************");
Console.WriteLine("Sum of the digit of the number = {0}",sum);
Console.WriteLine("************************");
Console.WriteLine("Reverse of the number = {0}",rev);
Console.WriteLine("************************");
if(n==rev)
Console.WriteLine("The number is a palindrome");
else
Console.WriteLine("The number is not a palindrome");
}
}

Generating Pascal Triangle

using System;
class pascalTriangle
{
public static void Main()
{
int binom=1,q=0,r,x;
Console.WriteLine("Enter the number of rows");
string s=Console.ReadLine();
int p =Int32.Parse(s);
Console.WriteLine(p);
Console.WriteLine("The Pascal Triangle");
while(q<p)
{
for(r=40-(3*q);r>0;--r)
Console.Write(" ");
for(x=0;x<=q;++x)
{
if((x==0)||(q==0))
binom=1;
else
binom=(binom*(q-x+1))/x;
Console.Write(binom);
}
Console.Write("\n ");
++q;
}
}
}

The following two source code listings showhow to write a crude but effective console mode application forconverting a number, either from binary to decimal, or from decimal tobinary. Note: you pass in the decimal number or the binary string as aparameter when typing the program's name at a command prompt.

From Decimal to Binary…

using System;

class Program{

static void Main(string[] args){

try{

int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));

}catch(Exception e){

Console.WriteLine("\n{0}\n",e.Message);

}

}//end Main

public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";

while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}

// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);

return BinaryResult;
}

}//end class Program

——————————————————————————–

From Binary to Decimal…

using System;

class Program{

static void Main(string[] args){

try{

int i = ToDecimal(args[0]);
Console.WriteLine("\n{0} converted to Decimal is {1}",args[0],i);

}catch(Exception e){

Console.WriteLine("\n{0}\n",e.Message);

}

}//end Main

public static int ToDecimal(string bin)
{
long l = Convert.ToInt64(bin,2);
int i = (int)l;
return i;
}

}//end class Program



//Binary equivalent of a binary number
#include<stdio.h>
#include<conio.h>
int binary (int);
void main()
{
int num;
clrscr();
printf("\nEnter The Number: ");
scanf("%d",&num);
binary(num);
printf("\n\n\n\n\nPress any key to exit.....");
getch();
}
//function to convert deciaml to binary
int binary (int n)
{
int r;
r=n%2;
n=n/2;
if (n==0)
{
printf("\nThe binary equivalent is %d",r);
return(r);
}
else
binary(n);
printf("%d",r);
}


We can achieve the string reversal in a easy way.

Let us Consider a one dimensional character array, input string and an output string variable.

Char[] arrStr;

string strInput = "Naveen";

string strOutput= string.Empty;


Am passing the string "Naveen" to the array in the following manner.

arrStr = strInput.ToCharArray();


then we have to put a reverse for loop like below

for(int idx=arrStr.Length-1;idx>=0; idx--)

{

   strOutput  += arrStr.Getvalue(idx);

}



The output will be "neevaN"


Reversing strings
First, there are many solutions, but this one can be done with three lines of code. The method shown in this article is based on the author's work with ToCharArray, and the method is static because it does not need to save state. This article is based on .NET 3.5 SP1.

=== Example program that reverses strings (C#) ===

using System;

static class StringHelper
{
    /// <summary>
    /// Receives string and returns the string with its letters reversed.
    /// </summary>
    public static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(StringHelper.ReverseString("framework"));
        Console.WriteLine(StringHelper.ReverseString("samuel"));
        Console.WriteLine(StringHelper.ReverseString("example string"));
    }
}

=== Output of the program ===

krowemarf
leumas
gnirts elpmaxe

What’s New in Visual C# 4.0

Visual C# version 4.0 offers new features that make it easier for you to work in dynamic programming scenarios. Besides dynamic programming, you have support for optional and named parameters, better COM interop support, and contra-variance and covariance. This article will show you how each of these features work and provide suggestions of
how they can be applied to help you be more productive.
To help you follow the path of C#, this article looks at the history of C#, today’s use of C#, and helps you understand the future of C# and what the language intends to provide for you. After you understand the theme of C# 4.0, you’ll learn about the new features of C# 4.0. Finally, this article will show you how to create a dynamic object of your own with late-bound calls to dynamic methods based on conventions.
C#: Then and Now
The previous major versions of C# were 1.0, 2.0, and 3.0. There was a minor version 1.1 in April of 2003, but it didn’t significantly change the theme of the 1.0 release. I’ll discuss these versions in the following sections.
Microsoft first announced C# on June 16th 2000. It was the first high-level programming language that was built specifically to target the .NET Common Language Runtime. C# 1.0 grew its heritage from C++, but borrowed features from languages such as Delphi, Java, and others. In C# 1.0, Microsoft planned to provide an object-oriented, component-based language that was very simple to use. When Microsoft released C# 1.0 to manufacturing on February 13th 2002, it was an immediate hit and steadily grew in popularity.
When C# 2.0 rolled around, Microsoft finally added all of the features that should have been in C# 1.0. For example, generics was huge and is an important part of .NET development today. C# 2.0 also introduced anonymous methods, iterators, and nullable types. An interesting addition to C# 2.0, nullable types was a pre-cursor feature for what was coming in the next version, focusing on data.
Most developers work with data, which was the primary theme of C# 3.0. The largest C# 3.0 language addition was Language Integrated Query (LINQ). Most other language features added in C# 3.0 were primarily to support LINQ, but the new features; including implicitly typed local variables, anonymous types, object and collection initializers, lambdas, and extension methods, can have value on their own in development that doesn’t involve LINQ.
The next version of C# will be 4.0, which is the focus of this article. C# 4.0 will primarily focus on dynamic programming. The following sections of this article explain the dynamic programming features of C# 4.0 as well as other new features such as optional/named parameters and covariance/contravariance.
Why Dynamic Programming?
The dynamic programming story in C# can fall into fulfilling categories of need in the way of multiple-language integration, simpler reflection, access to HTML DOM in Web scenarios, and easier COM interop. Some of these categories of need might not apply to your particular situation, and that’s okay because there isn’t anything that says that you have to use a language feature just because it’s there. Therefore, I’ll give you an idea of how someone with a specific need might find value in C# 4.0 dynamic programming.
"
C# 4.0 will primarily focus on dynamic programming.
"
Most C# developers use multiple tools in a single application to accomplish complex tasks. If you’re writing WPF desktop applications, you’re using C# and XAML. It is quite possible that you might find some open source code that solves a problem, but it might be written in another language such as VB or F#. One of the benefits of .NET since its inception is the ability to have cross-language interoperability and the runtime is even called the “Common Language” Runtime (CLR). In recent years, Microsoft has created dynamic languages, such as IronRuby and IronPython, but developers don’t have an easy way to perform interop with dynamic languages. If you have this need, then you’ll welcome the ease with which C# dynamic programming makes interop between C# and dynamic languages possible.
When performing reflection to run a method on an object, there are several hoops to jump through, including obtaining a reference to an object type, getting a reference to a member info object, determining the type of bindings to use, and then invoking the member. While reflection has an undeniable coolness factor, it still feels like a hack and that’s where C# 4.0 dynamic methods can help. Later in this article, I’ll show you how to just call the object member.
If you write Silverlight applications, you might have the need today or in the future to access the HTML DOM containing your Silverlight control. C# dynamic programming makes this task easier.
Performing COM interop with C# has always been cumbersome; partly because of the need to write extra syntax for conversions, optional parameters, and more. This has left some C# developers with a touch of VB envy because VB has easier COM interop support. One of the purposes of dynamic programming in C# is to help the C# programmer write cleaner syntax in COM interop scenarios.
I’ve spent some time explaining some of the potential benefits of dynamic programming because it’s so new that the value might not jump out at you immediately. In following sections, I’ll share the howso that you can match it up with the why that you might care about. Before diving into dynamic programming, let’s look at a couple other new features of C# 4.0, optional and named parameters.

Optional Parameters
"
If you’re of the same mind, then you’ll probably be pleased that C# 4.0 supports optional parameters.
"
For many C# developers, the long wait for optional parameters is over with C# 4.0. An optional parameter lets you provide a default value and the caller has a choice of whether or not they want to provide an argument. In current and earlier versions of C#, you could simulate optional parameters like this:
// Overload with no parameterpublic static string SayHello(){    return "Hey, You!";}
// Overload with normal parameterpublic static string SayHello(string name){    return "Hey, " + name + "!";}
The SayHello method above is overloaded with both an empty parameter list and a parameter list with a single string parameter. To the user of this code, the name parameter appears to be optional and both of the following calls work fine:
// Name is optionalvar greetYou = SayHello();
// Can provide name if you wantvar greetJoe = SayHello("Joe");
If you had methods with more parameters and wanted to provide a more flexible coding experience, you would provide more overloads. Many developers have said that this is cumbersome and leaves more code to maintain. If you’re of the same mind, then you’ll probably be pleased that C# 4.0 supports optional parameters. The snippet below shows an optional parameter, replacing the previous two overloads:
// Method with optional parameterpublic static string SayHello(string name = "You"){    return "Hey, " + name + "!";}
As shown in the previous snippet, the syntax to call an optional parameter requires assigning a default value to the parameter. In the listing above, "You" will be assigned to name if the caller does not provide a value.
A feature related to optional parameters is named parameters, which is discussed next.
Named Parameters
One of the primary purposes of named parameters is that they resolve ambiguity between parameters. For example, the following method contains two parameters that are strings:
public static void AddClubMember(    string name,     string email = "",     DateTime? dateJoined = null){    // Not yet implemented}
The types of the first two parameters of the AddClubMember method above are both string, except that name is not optional, but email is optional. This example also demonstrates that you can default parameters to null.
AddClubMember(    email: "joe@dot.net",     name: "Joe",     dateJoined: DateTime.Now);}
The call to AddClubMember above uses named parameters where the name is the same as the parameter name in the method declaration with an appended colon. Notice that I’ve shuffled the parameter order to demonstrate that you can change the order of parameters.
"
Named parameters are particularly useful when you have multiple optional parameters of the same type.
"
Named parameters are particularly useful when you have multiple optional parameters of the same type. In that case, you name the parameter that you want to set, telling C# which parameter your argument matches. The code below demonstrates a problem where named parameters are necessary:
AddClubMember(    "joe@dot.net",     dateJoined: DateTime.Now);}
If you recall, the first parameter of the AddClubMember method is name, a required parameter of type string. Since the first argument above is a string, C# will match that argument to the name parameter. Clearly, the value above is an email address, which presents you with a logical error that won’t be detected at either compile time nor run time when that line executes.

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | SharePoint Demo