The_Butcher The_Butcher - 1 month ago 5
C# Question

Is it more efficient to compare ints and ints or strings and strings

I've got a program written in c# where there are a lot of comparisons between ints and strings.

So for performance reasons, I would just like to know which is more efficient?

If we have:

int a = 5;
string b = "5";

if(a == int.Parse(b)) { }


OR

if(a.ToString() == b) { }

Ash Ash
Answer

A few comments mentioned running a profiling tool to prove which has better performance.

This is a ok, but the simplest way to check performance of specific statements is to put them in a loop and use the Stopwatch class.

Jeff Atwood asked about making this sort of timing even simpler in this question. In that question and answer you will also find some good code examples and background details.

Heres a very simple working example:

	System.Diagnostics.Stopwatch sw=new System.Diagnostics.Stopwatch();


	int a  = 5;
	string b = "5";

	sw.Start();

	for (int i=0;i<1000000;i++)
	{
		if(a == int.Parse(b))
		{

		} 
	}

	sw.Stop();

	Console.WriteLine("a == int.Parse(b) milliseconds: " + sw.ElapsedMilliseconds);

	sw.Reset();

	sw.Start();

	for (int i=0;i<1000000;i++)
	{
		if(a.ToString() == b)
		{

		}		
	}		

	sw.Stop();

	Console.WriteLine("a.ToString() == b milliseconds: " + sw.ElapsedMilliseconds);

On my computer it outputs:

a == int.Parse(b) milliseconds: 521

a.ToString() == b milliseconds: 697

So in this simple scenario int.Parse() is slightly faster, but not enough to really worry about.

Comments