Introduction

Lazy loading is a concept where we delay the loading of the object until the point where we need it. Putting in simple words, on demand object loading rather than loading objects unnecessarily.

For example, consider the below example where we have a simple Customer class and this Customer class has many Order objects inside it. Have a close look at the constructor of the Customer class. When the Customer object is created it also loads the Order object at that moment. So even if we need or do not need the Order object, it’s still loaded.

But how about just loading the Customer object initially and then on demand basis load the Order object?

 
public class Customer
{
private List<Order> _Orders= null;


public Customer()
{
_CustomerName = "Shiv";
_Orders = LoadOrders(); // Loads the order object even though //not needed
} private List<Order> LoadOrders()
{
List<Order> temp = new List<Order>();
Order o = new Order();
o.OrderNumber = "ord1001";
temp.Add(o);
o = new Order();
o.OrderNumber = "ord1002";
temp.Add(o);
return temp;
}
}

So let’s consider you have client code which consumes the Customer class as shown below. So when the Customer object is created no Order objects should be loaded at that moment. But as soon as the foreach loop runs you would like to load the Order object at that point (on demand object loading).

 
Customer o = new Customer(); // order object not loaded
Console.WriteLine(o.CustomerName);
foreach (Order o1 in o.Orders) // Load order object only at this moment
{
Console.WriteLine(o1.OrderNumber);
}

So how do we implement lazy loading?

For the above example if we want to implement lazy loading we will need to make the following changes:

  • Remove the Order object loading from the constructor.
  • In the Order get property, load the Order object only if it’s not loaded.
 
public class Customer
{
private List<Order> _Orders= null;


public Customer()
{
_CustomerName = "Shiv";
}
public List<Order> Orders
{
get
{
if (_Orders == null)
{
_Orders = LoadOrders();
}
return _Orders;
}
}

Now if you run the client code and halt your debugger just before the foreach loop runs over the Orders object, you can see the Orders object is null (i.e., not loaded). But as soon as the foreach loop runs over the Order object it creates the Order object collection.

Are there any readymade objects in .NET by which we can implement lazy loading?

In .NET we have the Lazy<T> class which provides automatic support for lazy loading. So let’s say if you want to implement Lazy<> in the above code, we need to implement two steps:

Create the object of orders using the Lazy generic class.

 
private Lazy<List<Order>> _Orders= null; 

Attach this Lazy<> object with the method which will help us load the order’s data.

 
_Orders = new Lazy<List<Order>>(() => LoadOrders());  

Now as soon as any client makes a call to the _Orders object, it will call the LoadOrders function to load the data.

You will get the List<orders> data in the Value property.

 
public List<Order> Orders
{
get
{
return _Orders.Value;
} }

Below goes the full code for this:

 
public class Customer
{
private Lazy<List<Order>> _Orders= null;
public List<Order> Orders
{
get
{
return _Orders.Value;
}
}
public Customer()
{
// Makes a database trip
_CustomerName = "Shiv";
_Orders = new Lazy<List<Order>>(() => LoadOrders());
}
}

What are the advantages and disadvantages of lazy loading?

Below are the advantages of lazy loading:

  • Minimizes start up time of the application.
  • Application consumes less memory because of on-demand loading.
  • Unnecessary database SQL execution is avoided.

The only one disadvantage is that the code becomes complicated. As we need to do checks if the loading is needed or not, there is a slight decrease in performance.

But the advantages are far more than the disadvantages.

FYI: The opposite of Lazy Loading is eager loading. So in eager loading we load all the objects in memory as soon as the object is created.

Also have a look at below posted video on Lazy Loading: -

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

原文链接:http://www.codeproject.com/Articles/652556/Can-you-explain-Lazy-Loading

本文地址:http://www.cnblogs.com/Interkey/articles/LazyLoading.html

.NET version 4.0 Framework or later and VS2010 or later is required for the Lazy class.

Lazy<T> Class: http://msdn.microsoft.com/en-us/library/dd642331(v=vs.100).aspx

建议阅读原文后面的 Comments and Discussions .

相关阅读:

http://www.cnblogs.com/Allen-Li/archive/2012/03/15/2398063.html

http://en.wikipedia.org/wiki/Lazy_loading

Can you explain Lazy Loading?的更多相关文章

  1. Angular2+typescript+webpack2(支持aot, tree shaking, lazy loading)

    概述 Angular2官方推荐的应该是使用systemjs加载, 但是当我使用到它的tree shaking的时候,发现如果使用systemjs+rollup,只能打包成一个文件,然后lazy loa ...

  2. Lazyr.js – 延迟加载图片(Lazy Loading)

    Lazyr.js 是一个小的.快速的.现代的.相互间无依赖的图片延迟加载库.通过延迟加载图片,让图片出现在(或接近))视窗才加载来提高页面打开速度.这个库通过保持最少选项并最大化速度. 在线演示    ...

  3. [AngularJS] Lazy Loading modules with ui-router and ocLazyLoad

    We've looked at lazy loading with ocLazyLoad previously, but what if we are using ui-router and want ...

  4. [AngularJS] Lazy loading Angular modules with ocLazyLoad

    With the ocLazyLoad you can load AngularJS modules on demand. This is very handy for runtime loading ...

  5. iOS swift lazy loading

    Why bother lazy loading and purging pages, you ask? Well, in this example, it won't matter too much ...

  6. Entity Framework加载相关实体——延迟加载Lazy Loading、贪婪加载Eager Loading、显示加载Explicit Loading

    Entity Framework提供了三种加载相关实体的方法:Lazy Loading,Eager Loading和Explicit Loading.首先我们先来看一下MSDN对三种加载实体方法的定义 ...

  7. Lazy Loading | Explicit Loading | Eager Loading in EntityFramework and EntityFramework.Core

    EntityFramework Eagerly Loading Eager loading is the process whereby a query for one type of entity ...

  8. EFCore Lazy Loading + Inheritance = 干净的数据表 (二) 【献给处女座的DB First程序猿】

    前言 本篇是上一篇EFCore Lazy Loading + Inheritance = 干净的数据表 (一) [献给处女座的DB First程序猿] 前菜 的续篇.这一篇才是真的为处女座的DB Fi ...

  9. EFCore Lazy Loading + Inheritance = 干净的数据表 (一) 【献给处女座的DB First程序猿】

    前言 α角 与 β角 关于α角 与 β角的介绍,请见上文 如何用EFCore Lazy Loading实现Entity Split. 本篇会继续有关于β角的彩蛋在等着大家去发掘./斜眼笑 其他 本篇的 ...

随机推荐

  1. 在线制作h5

    在线制作h5 官网:http://www.godgiftgame.com 在线制作h5首页预览效果图如下: 一.主要功能区域主要功能区域分布在上中左右三个地方,1.上面区域是功能选择区,包括图片素材. ...

  2. Debug Assertion Failed! Expression: _pFirstBlock == pHead

    点击Abort之后,查看调用栈,发现异常在函数return时被时产生,进一步看是vector的析构函数被调用时产生,以前没开发过C++项目,没什么经验,这个错误让我很困惑,第一,我电脑上并没有f盘:第 ...

  3. 分享7款非常实用的jQuery/CSS3插件演示和源码

    上次我们分享了15款效果很酷的最新jQuery/CSS3特效,非常不错,今天要分享7个非常实用的jQuery/CSS3插件演示和源码,一起来看看. 1.jQuery ajax点击地图显示商家网点分布 ...

  4. C++中文件按行读取和逐词读取 backup

    http://blog.csdn.net/zhangchao3322218/article/details/7930857 #include  <iostream>#include  &l ...

  5. MAC自带的SVN进行升级

    1.下载高版本svn:http://www.wandisco.com/subversion/download 2.安装 3. #1.在.bash_profile添加export PATH=/opt/s ...

  6. ux.plup.File plupload 集成 ux.plup.FileLis 批量上传预览

    //plupload 集成 Ext.define('ux.plup.File', { extend: 'Ext.form.field.Text', xtype: 'plupFile', alias: ...

  7. QT编写DLL给外部程序调用,提供VC/C#/C调用示例(含事件)

    最近这阵子,接了个私活,封装一个开发包俗称的SDK给客户调用,查阅了很多人家的SDK,绝大部分用VC编写,而且VC6.0居多,估计也是为了兼容大量的XP用户及IE浏览器,XP自带了VC6.0运行库,所 ...

  8. SkipList 跳表

    1.定义描述      跳跃列表(也称跳表)是一种随机化数据结构,基于并联的链表,其效率可比拟于二叉查找树(对于大多数操作需要O(log n)平均时间).      基本上,跳跃列表是对有序的链表增加 ...

  9. 协作图 Collaboration diagram

    概述 协作图也是一种交互图,但一般用的比较少,一般用在大概分析一下对象之间是怎样交互的,跟顺序图是可以相互转化的. 协作图的用处: 在分析的时候(而顺序图一般设计的时候),分析出有哪些对象: 在白板上 ...

  10. pptv破解版程序,能够免费观看所有蓝光和会员影片!

    pptv破解版程序,能够免费观看所有蓝光和会员影片!PPTV网络电视3.4.1.0012绿色版(去广告本地vip版)由Black Hawk精简破解,去掉播放时缓冲.暂停广告.去掉迷你推荐和推荐弹窗.禁 ...