什么是惰性分配? [英] what is lazy allocation?

查看:76
本文介绍了什么是惰性分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象的延迟分配是什么意思,它有什么用处?

What does lazy allocation of objects mean and how is it useful?

推荐答案

延迟分配只是意味着在实际需要资源之前不分配资源.这在单例对象中很常见,但严格来说,只要尽可能晚地分配资源,就会有一个延迟分配的例子.

Lazy allocation simply means not allocating a resource until it is actually needed. This is common with singleton objects, but strictly speaking, any time a resource is allocated as late as possible, you have an example of lazy allocation.

通过将资源的分配延迟到您真正需要它,您可以减少启动时间,甚至在您从未真正使用该对象的情况下完全消除分配.相比之下,你可以预先分配一个你预计以后需要的资源,这样可以以牺牲启动时间为代价让后面的执行更有效率,同时也避免了程序执行后期分配失败的可能性.

By delaying allocation of a resource until you actually need it, you can decrease startup time, and even eliminate the allocation entirely if you never actually use the object. In contrast, you could pre-allocate a resource you expect to need later, which can make later execution more efficient at the expense of startup time, and also avoids the possibility of the allocation failing later in program execution.

以下代码提供了一个延迟分配的单例示例:

The following code provides an example of a lazily-allocated singleton:

public class Widget {
    private Widget singleton;

    public static Widget get() {
        if (singleton == null) {
            singleton = new Widget();
        }
        return singleton;
    }

    private Widget() {
        // ...
    }

    // ...
}

请注意,此代码不是线程安全的.在大多数情况下,对 get() 方法的访问应该以某种方式同步.

Do note that this code isn't threadsafe. In most cases, access to the get() method should be synchronized in some fashion.

一个类似(也许更通用)的概念是延迟初始化.

A similar (and perhaps more general) concept is lazy initialization.

这篇关于什么是惰性分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆