Andrei Rinea

.NET Framework & SQL Server

Another C# riddle..

clock February 11, 2010 23:40 by author Andrei Rinea

Just like a little game of guessing went, I want to present you another C# riddle Cool :

using System;

namespace AnotherRiddle
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var w1 = new Wee { bar = new Foo() };
            if (w1.bar is Bar)
                Console.WriteLine("A");
            if (w1.bar.GetType() == typeof(Bar))
                Console.WriteLine("B");
        }
    }

    internal class Bar { }

    internal class Foo : Bar { }

    internal class Wee
    {
        public Bar bar;
    }
}

 

1. What do you think the code snippet will print at the console? 

2. What are all the differences between the two if constructs?



Request.UserHostAddress versus Request.ServerVariables["REMOTE_ADDR"]

clock February 10, 2010 08:59 by author Andrei Rinea

I just found out a HUGE performance difference between these two. Tested on my cheap laptop (HP Compaq 615 : AMD Turion Dual core 2,2GHz, 3GB RAM, 7200 RPM HDD; 500$) on .NET 4.0 Beta2 after several test runs (averaged results), 1 million iterations, release mode and Stopwatch for time measurement (as opposed to DateTime.Now) :

var a = Request.UserHostAddress; // -> 240 microseconds

var a = Request.ServerVariables["REMOTE_ADDR"]; // -> 0,4 microseconds

What the f...rick?! 500x times faster?

What does Request.UserHostAddress to use so much more time? Let's fire up good ol' Reflector :

	public string get_UserHostAddress()	
	{	    
	if (this._wr != null)	    
	{	        
	return this._wr.GetRemoteAddress();	    
	}	    
	return null;	
	}	
	

_wr is a HttpWorkerRequest (a public abstract class). The GetRemoteAddress is also abstract so I can't guess from Reflector. So I fired up Visual Studio 2010 again and saw that _wr was a Microsoft.VisualStudio.WebHost.Request instance. So much for my astonishment.. If it's hosted in the IDE it can be slow..

I still ponder if it's worth testing in a production environment whether it's faster or not (Request.UserHostAddress) significantly or not..

 

EDIT1 : Couldn't wait to test this at work under IIS 6.0 (Windows Server 2003, Intel Core2Duo 2,4 GHz, 4GB RAM) and Request.UserHostAddress takes 86 nanoseconds to be queried... Can't wait to get home and test again on IIS 7.5 (Windows 7 Ultimate RC)

 EDIT2: At home on IIS7.5, same laptop, release mode etc. etc. 29 microseconds for Request.UserHostAddress. It's better than Cassini's 240 microseconds but it should have been at most 100 nanoseconds...that's one thousand times slower..