Consider this example, it shows two possible ways of lazy initialization. Except for being thread-safe, are there any specific advantates of using Lazy<T> here?
class Customer {
private decimal? _balance2;
private static decimal GetBalanceOverNetwork() {
//lengthy network operations
Thread.Sleep(2000);
return 99.9M;
}
public decimal? GetBalance2Lazily() {
return _balance2 ?? (_balance2 = GetBalanceOverNetwork());
}
private readonly Lazy<decimal> _balance1 = new Lazy<decimal>(GetBalanceOverNetwork);
public Lazy<decimal> Balance1 {
get { return _balance1; }
}
}
UPDATE:
Please consider above code as a simple example, data types are irrelevant, the point here is to compare Lazy <T> over standard lazy initialization.
Lazy initialization is an excellent performance optimization technique, allowing you to defer the initialization of objects that consume significant CPU and memory resources until you absolutely need them. Take advantage of lazy initialization to improve the performance of your apps.
The Lazy<T> object ensures that all threads use the same instance of the lazily initialized object and discards the instances that are not used.
By default, Lazy<T> objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the Lazy<T> objects it creates are thread-safe.
Lazy Loading is a technique that delays the initialization of an object. This is a new feature of C# 4.0. The basic idea of lazy loading is to load objects or data only when they are needed. A lazy loading pattern is also called Object on Demand.
It is semantically more correct.
When you use the Nullable<decimal>
, what you say is that the value of null
will stand for the "unevaluated" state. Although this is a common conversion, it is still arbitrary. There are million other ways to interpret null
, so you should probably explain somewhere (in the documentation or at least as a comment) what null means in this case.
On the contrary, when you use Lazy<decimal>
, your intentions are clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With