Showing posts with label ASP.NET C#. Show all posts
Showing posts with label ASP.NET C#. Show all posts

Thursday, July 30, 2009

Mono for .Net on Mac

I am a .Net developer and with the new Mac, Mono has been inviting me for a long time now. With my baby's (long!) nap for an hour provided me with the opportunity to try out Mono and blog about it!

Why Mono?
1. A .Net developer since I learn to code - you know how addicted you can get to VS :)
2. A new Mac enthusiast


Steps to start trying out Mono
1. Get the installable from the go-mono site.
2. Run the installer. Mono installs under /Library/Frameworks/Mono.Framework
3. Here comes the famous 'Hello World'!!

using System;
public class Hello
{
static public void Main()
{
Console.WriteLine("Hello World, Here I come");
}
}
Note: For those of us .Net developers that hadn't worked in a shell terminal for a long time now, here are some of the notes to freshen up your memory!
  1. 1. vi filename - opens the vi editor with the filename
  2. 2. to save the file - :w
  3. 3. to quit the editor - :q
  4. 4. obviously, to save and quit - :wq (although, you would have figured it by now!)
4. Compile the code with - 'gmacs hello.cs'
5. Execute the code with - 'mono hello.exe'

There you go! Your first C# program on a Mac! Though simple, doesn't it thrill you?

Bang! Bang!! - The first time I compile the program - I got the error,
"`System.Console' does not contain a definition for `Writeline'". It took a full thirty seconds to spot the reason for the error - It should have been WriteLine!! Darn, VS has us fully spoiled!


Tuesday, April 28, 2009

DateTime.Now Vs. System.Diagnostics.Stopwatch

Occasionally all of us, as programmers would like to see how fast or how slow a C# function can execute. I am sure, most of us must have used DateTime.Now for the measurements. Roughly on these lines,

DateTime startTime = DateTime.Now;

// Some Execution Process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);


Now, does DateTime.Now accurately measure performance? No, it does not. DateTime.Now, according to MSDN has a resolution of ~16ms, which means it is not very precise.

Environment.TickCount
Another approach would to use system tickcount as kept by Environment.TickCount. This keeps the number of milliseconds since the computer was started. Unfortunately it is stored as a signed int, so every 49 days it is actually counting backwards. We can compensate for this by just taking off the most siginificant bit.

Stopwatch
Another better approach is to use Stopwatch. System.Diagnostics offers Stopwatch that automatically checks for high precision timers. You can check if the Stopwatch is using high-precision timers by checking via Stopwatch.IsHighResolution() method.


Stopwatch swTimer = Stopwatch.StartNew();
//Some execution process here
foo()
swTimer.Stop();


Watch for the difference in the code results

protected void Page_Load(object sender, EventArgs e)
{
DateTime sStartTime, sEndTime;
TimeSpan tsTotalTimeTaken;

sStartTime = DateTime.Now;
for (long lCount = 0; lCount < 100; lCount++)
{
Thread.Sleep(1);
}//for(int iCount=0; iCount<100; iCount++)

sEndTime = DateTime.Now;

Stopwatch swTimer = Stopwatch.StartNew();

for (long lCount = 0; lCount < 100; lCount++)
{
Thread.Sleep(1);
}//for(int iCount=0; iCount<100; iCount++)

swTimer.Stop();

tsTotalTimeTaken = sEndTime.Subtract(sStartTime);

Response.Write("Elaspsed Time according to DateTime.Now(): " + tsTotalTimeTaken.Milliseconds + "
");
Response.Write("Elapsed Time according to StopWatch(): " + swTimer.Elapsed.Milliseconds);
}



Output:

Wednesday, November 12, 2008

String Vs. StringBuilder classes

One of the .Net performance efficiency tip that we, developers keep hearing from all quarters is to use StringBuilder over String concatenates.

Now, lets see what actually happens behind the scenes. Are people right when they StringBuilder is better? Does it have a performance edge? If so, when?

Scenario 1:
String Concatenation
String sStringHolder = "";
Random rRandomize = new Random(150);

DateTime dtStartTime = System.DateTime.Now;
for (int iCount = 0; iCount < 10000; iCount++)
{
sStringHolder = sStringHolder + "1";
}//for(int iCount=0; iCount<1000; iCount++)
DateTime dtEndTime = System.DateTime.Now;

Trace.WriteLine("Time taken using the Concat operation >> 10000 Iterations: ");
Trace.WriteLine(((TimeSpan)(dtEndTime - dtStartTime)).Milliseconds);

dtStartTime = System.DateTime.Now;
for (int iCount = 0; iCount < 20000; iCount++)
{
sStringHolder = sStringHolder + "1";
}//for(int iCount=0; iCount<1000; iCount++)
dtEndTime = System.DateTime.Now;

Trace.WriteLine("Time taken using the Concat operation >> 20000 iterations: ");
Trace.WriteLine(((TimeSpan)(dtEndTime - dtStartTime)).Milliseconds);
The first iteration (for 10000 loops) took 46 milliseconds while the second iteration where the loop count doubled (20000 loops) increased almost 9 times (375 milliseconds).

So, what does really go on inside? Why are the results so drastically different?
sStringHolder = sStringHolder + "1";
Strings are immutable, i.e., the value can not modified once it is created. So, in this case three instance of the String objects are created to accommodate the concatenation. When a concat is performed, the old sStringHolder is discarded and a new one created to hold the newly concatenated string. That is the reason why it becomes too expensive.

Scenario 2
StringBuilder Goodness
StringBuilder sbStringHolder = new StringBuilder(50);

dtStartTime = System.DateTime.Now;
for (int iCount = 0; iCount < 50000; iCount++)
{
sbStringHolder.AppendFormat("{0}", "Hello");
}//for(int iCount=0; iCount < 1000; iCount++)
dtEndTime = System.DateTime.Now;

Trace.WriteLine("Time taken using StringBuilder class:AppendFormat >> 50000 iterations: ");
Trace.WriteLine(((TimeSpan)(dtEndTime - dtStartTime)).Milliseconds);
That was 15 milliseconds for a 50000 count iteration! StringBuilder certainly has an edge here.


This advantage that StringBuilder has is due to the fact that the string allocation and copies does not have to be as frequent as a String Concatenate. That's from where the majority of the savings come from. But if the StringBuilder has a buffer that's just right for the string that it holds, it will have to grow on every Append which is as good (or bad) as the string concatenate.

Although, this cannot be taken as a rule of thumb that StringBuilder is always more efficient than a String concatenation - Rico Mariani explains the four different cases.

Big string and small appends
=>It's substantially likely that appends will fit in the slop and so they're fast, this is the best case(buffer size becomes double the string when it no longer fits so on average the slop is half the current string length) (if there are lots of small appends to a big string you win the most using stringbuilder)

Big string and big appends:
=>While the string is comparable in size (or smaller) to the appends stringbuilder won't save you much, if this continues to the point where the appends are small compared to the accumlated string you're in the good case

Small string big appends:
=> bad case, string builder will just slow you down until enough slop has built up to hold those appends, you move to "big string big appends" as you append and finally to "big string small appends" if/when the buffer becomes collossal

Small string, small appends:
=> could be ok if you had a good idea how big your string was going to get and pre-allocated enough so that you have sufficient slop for the appends. You might be able to do better if you just concatenated all the small appends together in one operation.

Otherwise put, if the operation that is to be performed is something like this:
x = f(x) + f(y) + f(z) + f(a) - String Concat is better

If the operation will be something to this effect:
x += f(x);
x += f(y);
x += f(z);
x += f(a) - StringBuilder will suit better in this scenario

Thursday, November 6, 2008

The ?? Operator

Today was my first brush with the ?? operator and was pleasantly surprised by what it can do.


string sString1 = null;
string sString2 = "Hi";
string value = "";

// We would normally it this way
value = sString1 != null ? sString1 : sString2;

// Using ?? operator also called as coalescing
value = sString1 ?? sString2;

// In effect, it could be string
// val = a ?? b ?? c
// - The first non-null value is assigned to val
Response.Write(value);


Chaining ?? operator certainly makes it easier to perform a bunch of comparisons. When the ?? operator is chained, it assigns the value of the first non-null value.