I’m trying to develop some asynchronous methods for a personal project of mine, and I’m looking into the framework for reference.
I’ve downloaded the .NET source code to take a look at the bits and bolts more closely (with developer comments, something that Reflector doesn’t give us 😛 )
Anyway, in a lot of .NET classes I’ve came across the following pattern:
class SomeType
{
// ...
SomeClass m_Field;
// ...
SomeClass SomeMethod()
{
SomeClass localField = m_Field;
if (localField == null)
{
localField = new SomeClass();
m_Field = localField;
}
return localField;
}
}
That got me wondering what is the advantage of using such pattern?
As far as I know the pattern above is worse, performance wise, than the one below:
class SomeType
{
// ...
SomeClass m_Field;
// ...
SomeClass SomeMethod()
{
if (m_Field == null)
{
m_Field = new SomeClass();
}
return m_Field;
}
}
Or am I missing something here?
In many cases the difference is purely aesthetic and subjective, but three reasons to think about one vs. the other come to mind:
Thread Safety: A lockless algorithm might need to worry about this, but if all synchronization is done through locks, it shouldn’t be an issue.
Performance: It might be slightly faster in some cases, but I honestly doubt it will make a difference in most cases.
Exception Safety: Often you need to be careful to put intermediate changes into locals and then only publish the results to fields after the operations have completed without raising an exception. This acts as a transaction mechanism as nobody will see the object with only half of the fields set.