Just came across this .NET type – very cool.

If you’re creating types and are finding that they are quite heavy duty in terms of memory allocation, you might want to look at Lazy<T>. Example: –


Person is a type which has a large property on it – a 10K byte array. We are creating 100,000 of these Person objects in our PeopleFactory class – that’s around a gigabyte of memory gone, plus the time taken to allocate it etc.


You could normally get around this by doing stuff like this:-


This works just fine. Now, creating 100000 people uses up only 1.2MB; as soon as we access the property, we’ll inflate those objects to use the full 1GB. However, the pattern is pretty repetitive – imagine if we had dozens of properties etc..

Enter Lazy<T>. This handy type encapsulates this sort of logic for us; we can now rewrite our property like so: –


The Func<Byte[]> that is provided is what’s executed when the Value property is first accessed. So this simplifies your property accessors once again and gives you constructor-like creation in a lazy manner.

The memory usage is the same for the byte arrays, but there is a slightly higher memory footprint initially than in the manually-lazy loaded example above – Lazy<T> is a type in itself which requires memory, plus there’s the delegate to store the code to create the byte array.

However, Lazy<T> is still a useful tool – when you have many properties on a class and want to instantiate them in a lazy fashion e.g. perhaps you need to call a web service to retrieve the data, or go to the database etc. – using Lazy<T> can keep your properties easy to read and still give you lazy loading of them.

This very simple example doesn’t illustrate the full flexibility of the type – look at the MSDN article to see what else it can do.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s