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" 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
ActionScript 3 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 In C, lazy evaluation would normally be implemented inside one function, or one source file, using static variables.
In a function: #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; } Using one source file instead allows the state to be shared between multiple functions, while still hiding it from non-related functions.
: #pragma once
typedef struct Fruit { char* name; struct Fruit* next; int number; // Other members } Fruit;
Fruit* getFruit(char* name); void printFruitList(FILE* file);
: #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;
#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# In .NET Framework 4.0 Microsoft has included a System.Lazy class that can be used to do lazy loading. Below is some dummy code that does lazy loading of Class Fruit using System;
Lazy<Fruit> lazyFruit = new(); 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.
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 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
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();
A fairly straightforward 'fill-in-the-blanks' example of a Lazy Initialization design pattern, except that this uses an enumeration for the type 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; 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++ This example is in 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 //
Crystal 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 This example is in Haxe. 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]);
}Usageclass 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
This example is in 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