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) { }
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:
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.