Can the compiler optimize ToString () on a string?
I'm sure everyone has encountered their involvement with developers who love the method ToString()
. We've probably seen code similar to the following:
public static bool CompareIfAnyMatchesOrHasEmpty(List<string> list1, List<string> list2)
{
bool result = false;
foreach (string item1 in list1)
{
foreach (string item2 in list2)
{
if (item1.ToString() == item2.ToString())
{
result = true;
}
if (item1.ToString() == "")
{
result = true;
}
}
}
return result;
}
I'm wondering if a method ToString()
(empty, no formatting) can be optimized by the compiler? My guess is that this is not the case as it was originally defined on object
. So I provide this second question, if it would be worthwhile to try and clean up such instances?
source to share
These can certainly be optimized by the compiler, but they probably aren't because it's trivial. Before deciding whether to optimize, try some tests first. Try it!
List<string> strings = Enumerable.Range(1, 10000000).Select(x => Guid.NewGuid().ToString()).ToList();
var sw= Stopwatch.StartNew();
foreach (var str in strings) {
if (!str.ToString().Equals(str.ToString())) {
throw new ApplicationException("The world is ending");
}
}
sw.Stop();
Console.WriteLine("Took: " + sw.Elapsed.TotalMilliseconds);
sw = Stopwatch.StartNew();
foreach (var str in strings) {
if (!str.Equals(str)) {
throw new ApplicationException("The world is ending");
}
}
sw.Stop();
Console.WriteLine("Took: " + sw.Elapsed.TotalMilliseconds);
Ok, so we are in a loop with 10 million items. How long does the tostring (called twice) take compared to the non tostring version?
This is what I get on my machine:
Took: 261.6189
Took: 231.2615
So yes. I saved 30 milliseconds over 10 million iterations. So ... yeah, I'm going to say no, don't. At all.
Now if the code is changed because it is stupid? Yes. I would make an argument like this: "This is unnecessary and makes me think right away that this is NOT a string. I need brain loops to process it and it doesn't make sense. Don't argue from an optimization point of view.
source to share
The C # compiler will not optimize this. However, at runtime, I believe this will most likely be JIT compiled in the CLR as it string.ToString()
just returns itself.
String.ToString
is declared with TargetedPatchingOptOutAttribute
, which allows it to also embed in NGEN when called from other assemblies, so it is clearly an inline target.
source to share