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.

Lazy initialization

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.

Lazy initialization

In multithreaded code, access to lazy-initialized objects/state must be synchronized to guard against race conditions.

Lazy initialization

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 Usage: 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 a single function, or a single 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 a single 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;