Question: Is there a significant performance hit when assigning a variable to itself?
Although the code can be easily changed to avoid assigning a variable to itself or to use flags to detect how something should be assigned .. I like the use of a null coalescing operator to make cleaner initialization code. Consider the following code:
public class MyObject
{
public string MyString { get; set; }
}
public class Worker
{
Dictionary<int, string> m_cache = new Dictionary<string, string>();
public void Assign(ref MyObject obj)
{
string tmp = null;
if (some condition)
{
//can't pass in MyObject.MyString to out param, so we need to use tmp
m_cache.TryGetValue("SomeKey", out tmp); //assumption: key is guaranteed to exist if condition is met
}
else
{
obj.MyString = MagicFinder(); //returns the string we are after
}
//finally, assign MyString property
obj.MyString = tmp ?? obj.MyString;
//is there a significant performance hit here that is worth changing
//it to the following?
if (!string.IsEmptyOrNull(tmp))
{
obj.MyString = tmp;
}
}
}
Your question seems to boil down to this section:
To:
Realize, however, that the two versions are not the same. In the first case (using the null coalescing operation),
obj.MyStringcan get assigned tostring.Empty. The second case prevents this explicitly, since it’s checking againststring.IsNullOrEmpty, which will precent the assignment in the case of a non-null, empty string.Since the behavior is different, I would say this is not an optimization, but rather a behavioral change. Whether this is appropriate depends on the behavior this method is specified to demonstrate. How should empty strings be handled? That should be the determining factor here.
That being said, if you were to do an explicit null check, the performance would be near identical – I would suggest going for maintainability and readability here – to me, the first version is simpler, as it’s short and clear.
Also, looking at your code, I think it would be far simpler to put the assignment into the statement. This would make the code far more maintainable (and more efficient, to the delight of your boss…):
Given the assumption in the code (that the key will always exist in cache if your condition is true), you can even simplify this down to: