Hello, before I start to write just to remind you that we need a writer.So if you want to write on our blog please contact us at contact@zeusoft.net.
Ok, in this tutorial i will teach you how you can optimize your C# code.When you have a few “millions ” lines of code, your program may run slow.So you need to optimize your code using these tips:Loops
1. For loops is twice faster then foreach loops.That foreach loop:
static private void ForeachLoop(ArrayList SomeList)
{
int id = 0;
foreach (int i in List)
{
// Do something with the object ...
id = i;
}
}
is twice faster like that:
static private void ForLoop(ArrayList SomeList)
{
int id = 0;
int count = SomeList.Count;
for (int i = 0; i < SomeList.Count; i++)
{
// Do something with the object ...
id = (int)SomeList[i];
}
}
2. Boxing and unboxing
static private void BoxingAndUnboxing()
{
int i = 222;
object o = i; // Implicit boxing
i = 456; // Change the contents of i
int j = (int)o; // Unboxing (if types are incompatible this may trow an exception)
}
You dont have to use boxing and unboxing, and it’s faster:
static private void NoBoxingAndUnboxing()
{
int i = 123;
i = 456; // Change the contents of i
int j = i; // Compatible types
}
3.Exceptions
Trowing and catching an exception is 1000 slower than checking for an error code:
static void FunctionThatThrows()
{
throw new Exception();
}
1000 times faster
static int FunctionThatReturnsErrorCode()
{
return -1;
}
4.Collections
Using actual size for data rather than some default size increases performance up to 50%
ht = new Hashtable(count); // Creates an Hashtable using size = Count
LoadData(ht, count);
// Display results
Display.Show(1, "Elapsed time: " + t.ElapsedTime.ToString() + " ms \n", 0);
// End of the demo
Display.Show(-1, "Collections demo end.\n", 1);
static private void LoadData(Hashtable ht, int Count)
{
// Fill the employee collection with data
for (int i = 0; i < Count; i++)
{
Employee employee = new Employee(i, "Employee" + i.ToString());
ht.Add(i, employee);
}
}
5.Garbage collection
80% slower than doing nothing:
static private void Test(int count)
{
DisposableObject []obj = new DisposableObject[count];
for(int i=0;i
best solution:
static private voide LetDotnetCleanup(int count)
{
// Start performance timing
t.Start();
int count=int.Parse(args[0]);
DisposableObject []obj = new DisposableObject[count];
for(int i=0;i
6.Stack and Heap
N structures are Log(N) faster to allocate than N classes:
class ClassObject
{
public int x;
}
struct StructObject
{
public int x;
}
//alloc structs
tAllocation.Start();
for (i = 0; i < repeat; i++) // repeat to get more acurate timing
s = new StructObject();
tAllocation.Stop();
//alloc objects
for (i = 0; i < repeat; i++) // repeat to get more acurate timing
c = new ClassObject();
Reference: http://csharpcomputing.com/Tutorials/Lesson23.htm