Ленивая инициализация
В программировании ленивая инициализация — это тактика откладывания создания объекта , вычисления значения или другого ресурсоемкого процесса до момента, когда он впервые понадобится. Это разновидность ленивой оценки, которая относится конкретно к созданию экземпляров объектов или других ресурсов.
Обычно это достигается путем дополнения метода доступа (или геттера свойства) проверкой того, был ли уже инициализирован закрытый член, выступающий в роли кэша. Если да, то он возвращается немедленно. В противном случае создается новый экземпляр, помещается в переменную-член и возвращается вызывающей стороне непосредственно перед его первым использованием.
Если объекты обладают редко используемыми свойствами, это может повысить скорость запуска. Средняя производительность программы может быть немного хуже с точки зрения памяти (для переменных условий) и циклов выполнения (для их проверки), но влияние создания экземпляров объектов распределяется во времени («амортизируется»), а не концентрируется на этапе запуска системы, и, следовательно, медианное время отклика может быть значительно улучшено.
В многопоточном коде доступ к объектам/состоянию, инициализируемым с отложенной загрузкой, должен быть синхронизирован для предотвращения состояний гонки.
«Фабрика лени»
В контексте проектирования программного обеспечения ленивая инициализация часто используется вместе с паттерном фабричных методов. Это объединяет три идеи:
- Использование фабричного метода для создания экземпляров класса ( паттерн «фабричный метод» ).
- Сохранение экземпляров в карте и возврат одного и того же экземпляра каждому запросу для экземпляра с теми же параметрами ( паттерн «мультитон» ).
- Использование отложенной инициализации для создания экземпляра объекта при первом запросе (шаблон отложенной инициализации).
Примеры
ActionScript 3
Ниже приведён пример класса с ленивой инициализацией, реализованного на ActionScript:
package org.wikipedia.examples
{
public class Fruit
{
private var _typeName: String;
private static var instancesByTypeName: Dictionary = new Dictionary();
public function Fruit(typeName: String): void
{
this._typeName = typeName;
}
public function get typeName(): String
{
return _typeName;
}
public static function getFruitByTypeName(typeName: String): Fruit
{
return instancesByTypeName[typeName] ||= new Fruit(typeName);
}
public static function printCurrentTypes(): void
{
for each (var fruit: Fruit in instancesByTypeName)
{
// iterates through each value
trace(fruit.typeName);
}
}
}
}
Основное назначение:
package
{
import org.wikipedia.examples;
public class Main
{
public function Main(): void
{
Fruit.getFruitByTypeName("Banana");
Fruit.printCurrentTypes();
Fruit.getFruitByTypeName("Apple");
Fruit.printCurrentTypes();
Fruit.getFruitByTypeName("Banana");
Fruit.printCurrentTypes();
}
}
}
С
В языке C ленивая оценка обычно реализуется внутри одной функции или одного исходного файла с использованием статических переменных.
В функции:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct Fruit {
char* name;
struct Fruit* next;
int number;
// Other members
} Fruit;
Fruit* getFruit(char* name) {
static Fruit* fruitList;
static int seq;
Fruit* f = fruitList;
while (f) {
if (!strcmp(name, f->name)) {
return f;
}
f = f->next;
}
if (!(f = malloc(sizeof(Fruit)))) {
return NULL;
}
if (!(f->name = strdup(name))) {
free(f);
return NULL;
}
f->number = ++seq;
f->next = fruitList;
fruitList = f;
return f;
}
// Example code
int main(int argc, char* argv[]) {
Fruit* f;
if (argc < 2) {
fprintf(stderr, "Usage: fruits fruit-name [...]\n");
return 1;
}
for (int i = 1; i < argc; i++) {
if (f = getFruit(argv[i])) {
printf("Fruit %s: number %d\n", argv[i], f->number);
}
}
return 0;
}
Использование одного исходного файла позволяет совместно использовать состояние несколькими функциями, при этом скрывая его от несвязанных функций.
Fruit.h :
#pragma once
typedef struct Fruit {
char* name;
struct Fruit* next;
int number;
// Other members
} Fruit;
Fruit* getFruit(char* name);
void printFruitList(FILE* file);
Fruit.c :
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "Fruit.h"
static Fruit* fruitList;
static int seq;
struct Fruit* getFruit(char* name) {
Fruit* f = fruitList;
while (f) {
if (!strcmp(name, f->name)) {
return f;
}
f = f->next;
}
if (!(f = malloc(sizeof(Fruit)))) {
return NULL;
}
if (!(f->name = strdup(name))) {
free(f);
return NULL;
}
f->number = ++seq;
f->next = fruitList;
fruitList = f;
return f;
}
void printFruitList(FILE* file) {
Fruit* f = fruitList;
while (f) {
fprintf(file, "%4d %s\n", f->number, f->name);
f = f->next;
}
}
Main.c :
#include <stdlib.h>
#include <stdio.h>
#include "Fruit.h"
int main(int argc, char* argv[]) {
Fruit* f;
if (argc < 2) {
fprintf(stderr, "Usage: fruits fruit-name [...]\n");
return 1;
}
for (int i = 1; i < argc; i++) {
if (f = getFruit(argv[i])) {
printf("Fruit %s: number %d\n", argv[i], f->number);
}
}
printf("The following fruits have been generated:\n");
printFruitList(stdout);
return 0;
}
C#
В .NET Framework 4.0 компания Microsoft добавила System.Lazyкласс, который можно использовать для отложенной загрузки. Ниже приведён пример кода, демонстрирующий отложенную загрузку этого класса.Fruit
using System;
Lazy<Fruit> lazyFruit = new();
Fruit fruit = lazyFruit.Value;
Вот наглядный пример на C#.
Сам класс Fruitздесь ничего не делает. Переменная класса _typesDictionary — это символ Dictionary/, Mapиспользуемый для хранения Fruitэкземпляров typeName.
namespace Wikipedia.Examples;
using System;
using System.Collections;
using System.Collections.Generic;
class Fruit
{
private string _typeName;
private static IDictionary<string, Fruit> _typesDictionary = new Dictionary<string, Fruit>();
private Fruit(string typeName)
{
this._typeName = typeName;
}
public static Fruit GetFruitByTypeName(string type)
{
Fruit fruit;
if (!_typesDictionary.TryGetValue(type, out fruit))
{
// Lazy initialization
fruit = new(type);
_typesDictionary.Add(type, fruit);
}
return fruit;
}
public static void ShowAll()
{
if (_typesDictionary.Count > 0)
{
Console.WriteLine($"Number of instances made = {_typesDictionary.Count}");
foreach (KeyValuePair<string, Fruit> kvp in _typesDictionary)
{
Console.WriteLine(kvp.Key);
}
Console.WriteLine();
}
}
public Fruit()
{
// required so the sample compiles
}
}
public class Program
{
static void Main(string[] args)
{
Fruit.GetFruitByTypeName("Banana");
Fruit.ShowAll();
Fruit.GetFruitByTypeName("Apple");
Fruit.ShowAll();
// returns pre-existing instance from first
// time Fruit with "Banana" was created
Fruit.GetFruitByTypeName("Banana");
Fruit.ShowAll();
Console.ReadLine();
}
}
Довольно простой пример шаблона проектирования «ленивая инициализация» с возможностью заполнения пропусков, за исключением того, что здесь для типа используется перечисление .
namespace Wikipedia.Examples;
using System;
using System.Collections.Generic;
public class LazyFactoryObject
{
// internal collection of items
// IDictionary makes sure they are unique
private IDictionary<LazyObjectSize, LazyObject> _LazyObjectList =
new Dictionary<LazyObjectSize, LazyObject>();
// enum for passing name of size required
// avoids passing strings and is part of LazyObject ahead
public enum LazyObjectSize
{
None,
Small,
Big,
Bigger,
Huge
}
// standard type of object that will be constructed
public struct LazyObject
{
public LazyObjectSize Size;
public IList<int> Result;
}
// takes size and create 'expensive' list
private IList<int> Result(LazyObjectSize size)
{
IList<int> result = null;
switch (size)
{
case LazyObjectSize.Small:
result = CreateSomeExpensiveList(1, 100);
break;
case LazyObjectSize.Big:
result = CreateSomeExpensiveList(1, 1000);
break;
case LazyObjectSize.Bigger:
result = CreateSomeExpensiveList(1, 10000);
break;
case LazyObjectSize.Huge:
result = CreateSomeExpensiveList(1, 100000);
break;
case LazyObjectSize.None:
result = null;
break;
}
return result;
}
// not an expensive item to create, but you get the point
// delays creation of some expensive object until needed
private IList<int> CreateSomeExpensiveList(int start, int end)
{
IList<int> result = new List<int>();
for (int counter = 0; counter < (end - start); counter++)
{
result.Add(start + counter);
}
return result;
}
public LazyFactoryObject()
{
// empty constructor
}
public LazyObject GetLazyFactoryObject(LazyObjectSize size)
{
// yes, i know it is illiterate and inaccurate
LazyObject noGoodSomeOne;
// retrieves LazyObjectSize from list via out, else creates one and adds it to list
if (!_LazyObjectList.TryGetValue(size, out noGoodSomeOne))
{
noGoodSomeOne = new LazyObject();
noGoodSomeOne.Size = size;
noGoodSomeOne.Result = this.Result(size);
_LazyObjectList.Add(size, noGoodSomeOne);
}
return noGoodSomeOne;
}
}
C++
Этот пример написан на C++.
import std;
template <typename K, typename V>
using HashMap = std::unordered_map<K, V>;
template <typename T>
using SharedPtr = std::shared_ptr<T>;
using String = std::string;
class Fruit {
private:
static HashMap<String, SharedPtr<Fruit>> types = {};
String type;
// Note: constructor private forcing one to use static getFruit.
explicit Fruit(const String& type):
type{type} {}
public:
// Lazy Factory method, gets the Fruit instance associated with a certain type.
// Creates new ones as needed.
static SharedPtr<Fruit> getFruit(const String& type) {
auto [it, inserted] = types.emplace(type, nullptr);
if (inserted) {
it->second = std::make_shared<Fruit>(type);
}
return it->second;
}
// For example purposes to see pattern in action.
static void printCurrentTypes() {
std::println("Number of instances made = {}", types.size());
for (const auto& [type, fruit] : types) {
std::println({}, type);
}
std::println();
}
};
int main(int argc, char* argv[]) {
Fruit::getFruit("Banana");
Fruit::printCurrentTypes();
Fruit::getFruit("Apple");
Fruit::printCurrentTypes();
// Returns pre-existing instance from first time Fruit with "Banana" was
// created.
Fruit::getFruit("Banana");
Fruit::printCurrentTypes();
}
// OUTPUT:
//
// Number of instances made = 1
// Banana
//
// Number of instances made = 2
// Apple
// Banana
//
// Number of instances made = 2
// Apple
// Banana
//
Кристалл
class Fruit
private getter type : String
@@types = {} of String => Fruit
def initialize(@type)
end
def self.get_fruit_by_type(type : String)
@@types[type] ||= Fruit.new(type)
end
def self.show_all
puts "Number of instances made: #{@@types.size}"
@@types.each do |type, fruit|
puts "#{type}"
end
puts
end
def self.size
@@types.size
end
end
Fruit.get_fruit_by_type("Banana")
Fruit.show_all
Fruit.get_fruit_by_type("Apple")
Fruit.show_all
Fruit.get_fruit_by_type("Banana")
Fruit.show_all
Выход:
Number of instances made: 1 Banana Number of instances made: 2 Banana Apple Number of instances made: 2 Banana Apple
Хакс
class Fruit {
private static var _instances = new Map<String, Fruit>();
public var name(default, null):String;
public function new(name:String) {
this.name = name;
}
public static function getFruitByName(name:String):Fruit {
if (!_instances.exists(name)) {
_instances.set(name, new Fruit(name));
}
return _instances.get(name);
}
public static function printAllTypes() {
trace([for(key in _instances.keys()) key]);
}
}
Использование
class Test {
public static function main () {
var banana = Fruit.getFruitByName("Banana");
var apple = Fruit.getFruitByName("Apple");
var banana2 = Fruit.getFruitByName("Banana");
trace(banana == banana2); // true. same banana
Fruit.printAllTypes(); // ["Banana","Apple"]
}
}
Java
Этот пример не является потокобезопасным, см. страницу обсуждения. Вместо этого см. примеры в разделе Double-checked locking#Usage in Java. |
Этот пример написан на Java.
package org.wikipedia.examples;
import java.util.HashMap;
import java.util.Map;
enum FruitType {
NONE,
APPLE,
BANANA,
}
class Fruit {
private static Map<FruitType, Fruit> types = new HashMap<>();
/**
* Using a private constructor to force the use of the factory method.
* @param type
*/
private Fruit(FruitType type) {
}
/**
* Lazy Factory method, gets the Fruit instance associated with a certain
* type. Instantiates new ones as needed.
* @param type Any allowed fruit type, e.g. APPLE
* @return The Fruit instance associated with that type.
*/
public static Fruit getFruitByTypeName(FruitType type) {
Fruit fruit;
// This has concurrency issues. Here the read to types is not synchronized,
// so types.put and types.containsKey might be called at the same time.
// Don't be surprised if the data is corrupted.
if (!types.containsKey(type)) {
// Lazy initialisation
fruit = new Fruit(type);
types.put(type, fruit);
} else {
// OK, it's available currently
fruit = types.get(type);
}
return fruit;
}
/**
* Lazy Factory method, gets the Fruit instance associated with a certain
* type. Instantiates new ones as needed. Uses double-checked locking
* pattern for using in highly concurrent environments.
* @param type Any allowed fruit type, e.g. APPLE
* @return The Fruit instance associated with that type.
*/
public static Fruit getFruitByTypeNameHighConcurrentVersion(FruitType type) {
if (!types.containsKey(type)) {
synchronized (types) {
// Check again, after having acquired the lock to make sure
// the instance was not created meanwhile by another thread
if (!types.containsKey(type)) {
// Lazy initialisation
types.put(type, new Fruit(type));
}
}
}
return types.get(type);
}
/**
* Displays all entered fruits.
*/
public static void showAll() {
if (types.size() > 0) {
System.out.printf("Number of instances made = %d%n", types.size());
for (Map.Entry<FruitType, Fruit> entry : types.entrySet()) {
String fruit = entry.getKey().toString();
fruit = Character.toUpperCase(fruit.charAt(0)) + fruit.substring(1);
System.out.println(fruit);
}
System.out.println();
}
}
}
public class Program {
/**
* @param args
*/
public static void main(String[] args) {
Fruit.getFruitByTypeName(FruitType.BANANA);
Fruit.showAll();
Fruit.getFruitByTypeName(FruitType.APPLE);
Fruit.showAll();
Fruit.getFruitByTypeName(FruitType.BANANA);
Fruit.showAll();
}
}
Выход
Number of instances made = 1 Banana Number of instances made = 2 Banana Apple Number of instances made = 2 Banana Apple
JavaScript
Этот пример написан на JavaScript.
var Fruit = (function() {
var types = {};
function Fruit() {};
// count own properties in object
function count(obj) {
return Object.keys(obj).length;
}
var _static = {
getFruit: function(type) {
if (typeof types[type] == 'undefined') {
types[type] = new Fruit;
}
return types[type];
},
printCurrentTypes: function () {
console.log('Number of instances made: ' + count(types));
for (var type in types) {
console.log(type);
}
}
};
return _static;
})();
Fruit.getFruit('Apple');
Fruit.printCurrentTypes();
Fruit.getFruit('Banana');
Fruit.printCurrentTypes();
Fruit.getFruit('Apple');
Fruit.printCurrentTypes();
Выход
Number of instances made: 1 Apple Number of instances made: 2 Apple Banana Number of instances made: 2 Apple Banana
PHP
Вот пример отложенной инициализации в PHP 7.4:
<?php
header('Content-Type: text/plain; charset=utf-8');
class Fruit
{
private string $type;
private static array $types = array();
private function __construct(string $type)
{
$this->type = $type;
}
public static function getFruit(string $type): Fruit
{
// Lazy initialization takes place here
if (!isset(self::$types[$type])) {
self::$types[$type] = new Fruit($type);
}
return self::$types[$type];
}
public static function printCurrentTypes(): void
{
echo 'Number of instances made: ' . count(self::$types) . "\n";
foreach (array_keys(self::$types) as $key) {
echo "$key\n";
}
echo "\n";
}
}
Fruit::getFruit('Apple');
Fruit::printCurrentTypes();
Fruit::getFruit('Banana');
Fruit::printCurrentTypes();
Fruit::getFruit('Apple');
Fruit::printCurrentTypes();
/*
OUTPUT:
Number of instances made: 1
Apple
Number of instances made: 2
Apple
Banana
Number of instances made: 2
Apple
Banana
*/
Python
Этот пример написан на Python.
class Fruit:
def __init__(self, item: str) -> None:
self.item = item
class FruitCollection:
def __init__(self) -> None:
self.items: dict[str, Fruit] = {}
def get_fruit(self, item: str) -> Fruit:
if item not in self.items:
self.items[item] = Fruit(item)
return self.items[item]
if __name__ == "__main__":
fruits: FruitCollection = FruitCollection()
print(fruits.get_fruit("Apple"))
print(fruits.get_fruit("Lime"))
Руби
Этот пример написан на Ruby и демонстрирует ленивую инициализацию токена аутентификации из удалённого сервиса, например, Google. Способ кэширования @auth_token также является примером мемоизации.
require 'net/http'
class Blogger
def auth_token
@auth_token ||=
(res = Net::HTTP.post_form(uri, params)) &&
get_token_from_http_response(res)
end
# get_token_from_http_response, uri and params are defined later in the class
end
b = Blogger.new
b.instance_variable_get(:@auth_token) # returns nil
b.auth_token # returns token
b.instance_variable_get(:@auth_token) # returns token
Ржавчина
Ржавчина имеет std::cell::LazyCell. [2]
use std::cell::LazyCell;
let lazy: LazyCell = LazyCell::new(|| 42);
Скала
В Scala есть встроенная поддержка ленивой инициализации переменных. [3]
scala> val x = { println("Hello"); 99 }
Hello
x: Int = 99
scala> lazy val y = { println("Hello!!"); 31 }
y: Int = <lazy>
scala> y
Hello!!
res2: Int = 31
scala> y
res3: Int = 31
Неформальный разговор
This example is in Smalltalk, of a typical метод доступа to return the value of a variable using lazy initialization.
height
^height ifNil: [height := 2.0].
«Неленивая» альтернатива заключается в использовании метода инициализации, который выполняется при создании объекта, а затем использовании более простого метода доступа для получения значения.
initialize
height := 2.0
height
^height
Следует отметить, что ленивая инициализация может использоваться и в языках, не являющихся объектно-ориентированными.
Теоретическая информатика
In the field of теоретической информатики, ленивая инициализация[4] (also called a ленивым массивом) is a technique to design структур данных that can work with memory that does not need to be initialized. Specifically, assume that we have access to a table T of n uninitialized memory cells (numbered from 1 to n), and want to assign m cells of this array, e.g., we want to assign T[ki] := vi for pairs (k1, v1), ..., (kопераций, vm) with all kразличны being different. The lazy initialization technique allows us to do this in just O(m) operations, rather than spending O(m+операций) operations to first initialize all array cells. The technique is simply to allocate a table V storing the pairs (ki, vi) in some arbitrary order, and to write for each i in the cell T[ki] the position in V where key ki is stored, leaving the other cells of T uninitialized. This can be used to handle queries in the following fashion: when we look up cell T[k] for some k, we can check if T[k] is in the range {1, ..., m}: if it is not, then T[k] is uninitialized. Otherwise, we check V[T[k]], and verify that the first component of this pair is equal to k. If it is not, then T[k] is uninitialized (and just happened by accident to fall in the range {1, ..., m}). Otherwise, we know that T[k] is indeed one of the initialized cells, and the corresponding value is the second component of the pair.
См. также
Ссылки
- ↑ «Ленивая инициализация — Шаблоны проектирования — Справочник по языку программирования Haxe». 2018-01-11. Дата обращения: 2018-11-09.
- ↑ "LazyCell в std::cell - Rust". doc.rust-lang.org. Retrieved 18 января 2025.
- ↑ Pollak, David (2009-05-25). Начало изучения Scala. Apress. ISBN 9781430219897.
- ↑ Moret, B. M. E.; Shapiro, H. D. (1991). Алгоритмы от P до NP, том 1: проектирование и эффективность. Benjamin/Cummings Publishing Company. pp. 191–192. ISBN 0-8053-8008-6.
Внешние ссылки
- Статья « Совет Java № 67: Ленивая инициализация экземпляров — баланс между производительностью и использованием ресурсов» Филипа Бишопа и Найджела Уоррена.
- Примеры кода на Java
- Используйте отложенную инициализацию для экономии ресурсов.
- Описание из хранилища образцов Портленда.
- Ленивая инициализация служб сервера приложений
- Ленивое наследование в JavaScript
- Ленивое наследование в C#
Источники
- Участники английской Википедии. «Lazy initialization». Перевод на русский. CC BY-SA 4.0 (текст и перевод).
