Caching Intensive calculation in Getter properties

In the following code:

public class SomeClass { // ... constructor and other stuff public in SomeProperty { get { return SomeHeayCalculation(); } } } 

I consider the class immutable, so every time I call SomeProperty , the same value is returned. My question is whether it is possible to calculate the value each time. Is there a built-in caching mechanism for such materials?

+6
source share
4 answers

Yup - Lazy<T> , assuming you are using .NET 4:

 public class SomeClass { private readonly Lazy<Foo> foo = new Lazy<Foo>(SomeHeayCalculation); // ... constructor and other stuff public Foo SomeProperty { get { return foo.Value; } } } 

I assume that you are trying to avoid doing the calculation if the property never accesses. Otherwise, just follow it when building.

Note that properties are often understood to be β€œcheap” for pricing β€” and while you are doing it lazy so that later calls are cheap, it will still potentially be β€œheavy” enough for the first access to make the property inappropriate. Instead, consider the ComputeXyz method.

+15
source

Just cache the calculation in a private variable like this:

 public class SomeClass { // ... constructor and other stuff private int? calculation = null; public int SomeProperty { get { if (!calculation.HasValue) calculation = SomeHeayCalculation(); return calculation.Value; } } } 
+4
source

Besides what John suggested, you can use this template:

 public class SomeClass { // ... constructor and other stuff private Foo _foo; public Foo SomeProperty { get { return _foo ?? (_foo = SomeHeayCalculation()); } } } 

It's worth noting that this really breaks (reading: becomes less readable) for value types if you don't want to wrap them in Nullable<T> . In this case, you can stick with Lazy<T> if available.

+2
source

Just save the flag to remember if calculations have been made.

 public class SomeClass { // ... constructor and other stuff private bool _propertyCalculated; private int _someProperty; public int SomeProperty { get { if (!_propertyCaculated) { _someProperty = SomeHeayCalculation(); _propertyCaculated = true; } return _someProperty; } } } 
+1
source

Source: https://habr.com/ru/post/894025/


All Articles