질문 : 변수를 자체에 할당 할 때 중요한 성능이 저하됩니까?변수 자체를 할당 할 수있는 할당 문의 효율성 문제
코드는 쉽게 변수를 할당하거나 플래그를 사용하여 무언가를 지정해야하는 것을 피하기 위해 쉽게 변경할 수 있지만 null 통합 연산자를 사용하여보다 명확한 초기화 코드를 작성하는 것이 좋습니다. 다음 코드를 고려하십시오.
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;
}
}
}
무엇이 질문입니까? – svick
나는 이것이 문제라고 생각한다. (출처를 보라) : "여기에 상당한 성능 저하가 있었는데, 다음과 같이 변경해야 할 가치가 있는가?" – Lucero
사과드립니다. 나는 명확한 하나의 라이너를 만들었어야했는데, Lucero는 정확하다. –