Lazy loaded properties are checked.

In a class that has a lazy loaded property, for example:

private Collection<int> someInts; public Collection<int> SomeInts { get { if (this.someInts == null) this.someInts = new Collection<int>(); return this.someInts; } } 

Is it worth it to also have such a property as:

 public bool SomeIntsExist { get { return (this.someInts != null && this.someInts.Count > 0); } } 

And then using this property .. for example:

 if (thatClass.SomeIntsExist) { // do something with thatClass.SomeInts collection } 

or is it premature optimization. It is certainly easier to roll with something like below, but it will instantiate the collection to no avail:

 if (thatClass.SomeInts.Count > 0) { // do something with thatClass.SomeInts collection } 

Is the compiler smart enough to understand such things? Is there a better way?

+4
source share
4 answers

Even lazy property initialization sounds like premature optimization. There are very few cases where I can think that delaying the creation of an empty collection helps solve the problem (assuming your example is not simplified).

But when you need to defer collection initialization, you probably have to (or even have to) optimize the Exists method, because lazy initialization is a critical requirement.

+2
source

The compiler will not automatically expose such things. This means that in the latter case

 if (thatClass.SomeInts.Count > 0) { // do something with thatClass.SomeInts collection } 

An instance of the collection will be created.

So, in my opinion, it depends on how expensive the initialization of the collection is - in the simple case it is not very expensive, but lost memory can summarize ...

+1
source

I would say that it is worth having such properties if you are dealing with expensive data extraction, for example. database queries.

However, there are flaws in your code. SomeIntsExist only ever really give you the correct answer, if the property was previously requested, if the property will be loaded with laziness, then there may indeed be integers, but they have not yet been loaded. It should be renamed to something like IsInitialised . I know this example, but probably worth noting:

+1
source

if the lazy loaded class is big and initialization takes some time ... such a boolean value.

bin in the case of a simple .net collection, in my opinion, it does not.

0
source

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


All Articles