ZZ: C# LAZY OBJ说明

“Lazy Instantiation” defers creation of an object till the time it is actually accessed.The process of object creation is always expensive as it involves allocation of memory on the heap.So Lazy Instantiation optimizes resources by using them when it is actually required.

 使用延迟初始化来推迟创建大或非常耗费资源的对象或通过执行资源密集型任务中,尤其是在此类创建,或者执行可能会出现该程序的生存期内时。

C#4.0:

IsValueCreated to check whether the object was actually created.

class Program
{
    static void Main(string[] args)
    {
        Lazy<Foo> f = new Lazy<Foo>( );
        Console.WriteLine("Foo is defined");
        if (!f.IsValueCreated) Console.WriteLine("Foo is not initialized yet..");
        Console.WriteLine("Foo::ID=" + (f.Value as Foo).ID);
        if (f.IsValueCreated) Console.WriteLine("Foo is initialized now..");
        Console.Read();
    }
}

public class Foo
{
    public int ID { get; set; }

    public Foo()
    {
        Console.WriteLine("Foo:: Constructor is called");
        ID = 1;
    }
}

延迟实例化,延迟初始化等,主要表达的思想是,把对象的创建将会延迟到使用时创建,而不是在对象实例化时创建对象,即用时才加载。这种方式有助于提高于应用程序的性能,避免浪费计算,节省内存的使用等。

当创建一个对象的子对象开销比较大时,而且有可能在程序中用不到这个子对象,那么可以考虑用延迟加载的方式来创建子对象。另外一种情况就是当程序一启动时,需要创建多个对象,但仅有几个对象需要立即使用,这样就可以将一些不必要的初始化工作延迟到使用时,这样可以非常有效的提高程序的启动速度。

在搜索产品的开发测试过程中,经常涉及大数据量的读写。而如果直接读取大文件,往往会导致程序崩溃。这时候Lazy属性就起到了非常关键的作用。

猜你喜欢

转载自blog.csdn.net/narlon/article/details/80745120
zz