Lazy initialization
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.
This is typically accomplished by augmenting an accessor method (or property getter) to check whether a private member, acting as a cache, has already been initialized. If it has, it is returned straight away. If not, a new instance is created, placed into the member variable, and returned to the caller just-in-time for its first use.
If objects have properties that are rarely used, this can improve startup speed. Mean average program performance may be slightly worse in terms of memory (for the condition variables) and execution cycles (to check them), but the impact of object instantiation is spread in time ("amortized") rather than concentrated in the startup phase of a system, and thus median response times can be greatly improved.
In multithreaded code, access to lazy-initialized objects/state must be synchronized to guard against race conditions.
The "lazy factory"
[edit]In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:
- Using a factory method to create instances of a class (factory method pattern)
- Storing the instances in a map, and returning the same instance to each request for an instance with same parameters (multiton pattern)
- Using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern)
Examples
[edit]ActionScript 3
[edit]The following is an example of a class with lazy initialization implemented in ActionScript:
package examples.lazyinstantiation
{
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);
}
}
}
}
Basic use:
package
{
import examples.lazyinstantiation;
public class Main
{
public function Main():void
{
Fruit.getFruitByTypeName("Banana");
Fruit.printCurrentTypes();
Fruit.getFruitByTypeName("Apple");
Fruit.printCurrentTypes();
Fruit.getFruitByTypeName("Banana");
Fruit.printCurrentTypes();
}
}
}
C
[edit]In C, lazy evaluation would normally be implemented inside one function, or one source file, using static variables.
In a function:
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
struct fruit {
char *name;
struct fruit *next;
int number;
/* Other members */
};
struct fruit *get_fruit(char *name) {
static struct fruit *fruit_list;
static int seq;
struct fruit *f;
for (f = fruit_list; f; f = f->next)
if (0 == strcmp(name, f->name))
return f;
if (!(f = malloc(sizeof(struct fruit))))
return NULL;
if (!(f->name = strdup(name))) {
free(f);
return NULL;
}
f->number = ++seq;
f->next = fruit_list;
fruit_list = f;
return f;
}
/* Example code */
int main(int argc, char *argv[]) {
int i;
struct fruit *f;
if (argc < 2) {
fprintf(stderr, "Usage: fruits fruit-name [...]\n");
exit(1);
}
for (i = 1; i < argc; i++) {
if ((f = get_fruit(argv[i]))) {
printf("Fruit %s: number %d\n", argv[i], f->number);
}
}
return 0;
}
Using one source file instead allows the state to be shared between multiple functions, while still hiding it from non-related functions.
fruit.h:
#ifndef _FRUIT_INCLUDED_
#define _FRUIT_INCLUDED_
struct fruit {
char *name;
struct fruit *next;
int number;
/* Other members */
};
struct fruit *get_fruit(char *name);
void print_fruit_list(FILE *file);
#endif /* _FRUIT_INCLUDED_ */
fruit.c:
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include "fruit.h"
static struct fruit *fruit_list;
static int seq;
struct fruit *get_fruit(char *name) {
struct fruit *f;
for (f = fruit_list; f; f = f->next)
if (0 == strcmp(name, f->name))
return f;
if (!(f = malloc(sizeof(struct fruit))))
return NULL;
if (!(f->name = strdup(name))) {
free(f);
return NULL;
}
f->number = ++seq;
f->next = fruit_list;
fruit_list = f;
return f;
}
void print_fruit_list(FILE *file) {
struct fruit *f;
for (f = fruit_list; f; f = f->next)
fprintf(file, "%4d %s\n", f->number, f->name);
}
main.c:
#include <stdlib.h>
#include <stdio.h>
#include "fruit.h"
int main(int argc, char *argv[]) {
int i;
struct fruit *f;
if (argc < 2) {
fprintf(stderr, "Usage: fruits fruit-name [...]\n");
exit(1);
}
for (i = 1; i < argc; i++) {
if ((f = get_fruit(argv[i]))) {
printf("Fruit %s: number %d\n", argv[i], f->number);
}
}
printf("The following fruits have been generated:\n");
print_fruit_list(stdout);
return 0;
}
C#
[edit]In .NET Framework 4.0 Microsoft has included a Lazy
class that can be used to do lazy loading.
Below is some dummy code that does lazy loading of Class Fruit
var lazyFruit = new Lazy<Fruit>();
Fruit fruit = lazyFruit.Value;
Here is a dummy example in C#.
The Fruit
class itself doesn't do anything here, The class variable _typesDictionary
is a Dictionary/Map used to store Fruit
instances by typeName
.
using System;
using System.Collections;
using System.Collections.Generic;
public 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 Fruit(type);
_typesDictionary.Add(type, fruit);
}
return fruit;
}
public static void ShowAll()
{
if (_typesDictionary.Count > 0)
{
Console.WriteLine("Number of instances made = {0}", _typesDictionary.Count);
foreach (KeyValuePair<string, Fruit> kvp in _typesDictionary)
{
Console.WriteLine(kvp.Key);
}
Console.WriteLine();
}
}
public Fruit()
{
// required so the sample compiles
}
}
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();
}
}
A fairly straightforward 'fill-in-the-blanks' example of a Lazy Initialization design pattern, except that this uses an enumeration for the type
namespace DesignPatterns.LazyInitialization;
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;
default:
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++
[edit]This example is in C++.
import std;
class Fruit {
public:
static Fruit* GetFruit(const std::string& type);
static void PrintCurrentTypes();
private:
// Note: constructor private forcing one to use static |GetFruit|.
Fruit(const std::string& type) : type_(type) {}
static std::map<std::string, Fruit*> types;
std::string type_;
};
// static
std::map<std::string, Fruit*> Fruit::types;
// Lazy Factory method, gets the |Fruit| instance associated with a certain
// |type|. Creates new ones as needed.
Fruit* Fruit::GetFruit(const std::string& type) {
auto [it, inserted] = types.emplace(type, nullptr);
if (inserted) {
it->second = new Fruit(type);
}
return it->second;
}
// For example purposes to see pattern in action.
void Fruit::PrintCurrentTypes() {
std::println("Number of instances made = {}", types.size());
for (const auto& [type, fruit] : types) {
std::println({}, type);
}
std::println();
}
int main() {
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
//
Crystal
[edit]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
Output:
Number of instances made: 1 Banana Number of instances made: 2 Banana Apple Number of instances made: 2 Banana Apple
Haxe
[edit]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]);
}
}
Usage
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
[edit]This example is not thread-safe, see the talk page. Instead see the examples in Double-checked locking#Usage in Java. |
This example is in Java.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
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();
}
}
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.println("Number of instances made = " + types.size());
for (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();
}
}
}
Output
Number of instances made = 1 Banana Number of instances made = 2 Banana Apple Number of instances made = 2 Banana Apple
JavaScript
[edit]This example is in 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();
Output
Number of instances made: 1 Apple Number of instances made: 2 Apple Banana Number of instances made: 2 Apple Banana
PHP
[edit]Here is an example of lazy initialization in 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)
{
// 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
[edit]This example is in Python.
class Fruit:
def __init__(self, item: str):
self.item = item
class FruitCollection:
def __init__(self):
self.items = {}
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()
print(fruits.get_fruit("Apple"))
print(fruits.get_fruit("Lime"))
Ruby
[edit]This example is in Ruby, of lazily initializing an authentication token from a remote service like Google. The way that @auth_token is cached is also an example of memoization.
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
Scala
[edit]Scala has built-in support for lazy variable initiation.[2]
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
Smalltalk
[edit]This example is in Smalltalk, of a typical accessor method to return the value of a variable using lazy initialization.
height
^height ifNil: [height := 2.0].
The 'non-lazy' alternative is to use an initialization method that is run when the object is created and then use a simpler accessor method to fetch the value.
initialize
height := 2.0
height
^height
Note that lazy initialization can also be used in non-object-oriented languages.
Theoretical computer science
[edit]In the field of theoretical computer science, lazy initialization[3] (also called a lazy array) is a technique to design data structures 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), ..., (km, vm) with all ki being different. The lazy initialization technique allows us to do this in just O(m) operations, rather than spending O(m+n) 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 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.
See also
[edit]References
[edit]- ^ "Lazy initialization - Design patterns - Haxe programming language cookbook". 2018-01-11. Retrieved 2018-11-09.
- ^ Pollak, David (2009-05-25). Beginning Scala. Apress. ISBN 9781430219897.
- ^ Moret, B. M. E.; Shapiro, H. D. (1991). Algorithms from P to NP, Volume 1: Design & Efficiency. Benjamin/Cummings Publishing Company. pp. 191–192. ISBN 0-8053-8008-6.
External links
[edit]- Article "Java Tip 67: Lazy instantiation - Balancing performance and resource usage" by Philip Bishop and Nigel Warren
- Java code examples
- Use Lazy Initialization to Conserve Resources
- Description from the Portland Pattern Repository
- Lazy Initialization of Application Server Services
- Lazy Inheritance in JavaScript
- Lazy Inheritance in C#