지연된 초기화

지연된 초기화, 게으른 초기화(lazy initialization)은 컴퓨터 프로그래밍에서 객체 생성, 값 계산, 또는 일부 기타 비용이 많이 드는 과정을 처음 필요한 시점까지 지연시키는 기법이다. 즉, 처음 필요할 때까지 객체 생성, 값 계산 또는 기타 비용이 많이 드는 프로세스를 지연시키는 전술이다. 이는 특히 개체나 기타 리소스의 인스턴스화를 참조하는 일종의 지연 평가이다.

이는 일반적으로 접근자 메서드(또는 속성 getter)를 확장하여 캐시 역할을 하는 전용 멤버가 이미 초기화되었는지 확인함으로써 수행된다. 초기화가 되었다면 즉시 반환된다. 그렇지 않은 경우 새 인스턴스가 생성되어 멤버 변수에 배치되고 처음 사용하기 위해 적시에 호출자에게 반환된다.

개체에 거의 사용되지 않는 속성이 있는 경우 시작 속도가 향상될 수 있다. 평균 평균 프로그램 성능은 메모리(조건 변수의 경우) 및 실행 주기(확인용) 측면에서 약간 더 나쁠 수 있지만 객체 인스턴스화의 영향은 시스템의 시작 단계에 집중되지 않고 시간에 따라 분산되므로 중앙 응답 시간이 크게 향상될 수 있다.

다중 스레드 코드에서는 지연 초기화된 개체/상태에 대한 액세스를 동기화하여 경쟁 조건을 방지해야 한다.

예시

액션스크립트 3

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);
			}
		}
	}
}

기본 사용법:

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

함수에서:

#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;
}

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;
}

Haxe

Haxe의 예는 다음과 같다:[1]

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"]
  }
}

같이 보기

각주

  1. “Lazy initialization - Design patterns - Haxe programming language cookbook” (영어). 2018년 1월 11일. 2018년 11월 9일에 확인함. 

외부 링크

Read other articles:

Forma de colocar la cuchara y el terrón de azúcar. Cucharas de absenta. La cuchara de absenta sirve para la preparación de esta bebida. Cuando se va a tomar, se pone un terrón de azúcar sobre la cuchara, colocada sobre el vaso, vertiendo agua encima lentamente, con la finalidad de atenuar el sabor amargo de la absenta. La cuchara es plana y con agujeros, y puede tener distintas formas, como, por ejemplo, la Torre Eiffel, hojas de árbol, etc. Este tipo de cuchara no puede ser anterior a ...

 

Локсодрома від полюса до полюса Ця стаття не містить посилань на джерела. Ви можете допомогти поліпшити цю статтю, додавши посилання на надійні (авторитетні) джерела. Матеріал без джерел може бути піддано сумніву та вилучено. (липень 2021) Локсодрома — лінія на поверхн...

 

Canadian rock singer Michel PagliaroPagliaro at Les FrancoFolies de Montréal in 2008Background informationBorn (1948-11-09) 9 November 1948 (age 75)Montreal, Quebec, CanadaOccupation(s)Singer, songwriter and guitaristYears active1966–presentLabelsDCP InternationalSpectrumMuchRCAColumbia(also Pye in the UK and US, and Columbia in US; French-language recordings bear the CBS brand)Websitepagliaro.caMusical artist Michel Armand Guy Pagliaro (born 9 November 1948)[1] is a Canadian ...

العلاقات الغيانية الميانمارية غيانا ميانمار   غيانا   ميانمار تعديل مصدري - تعديل   العلاقات الغيانية الميانمارية هي العلاقات الثنائية التي تجمع بين غيانا وميانمار.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه المقار...

 

Alaska DOT&PF seal Government agency in Alaska, United States Alaska Department of Transportation & Public Facilities (DOT&PF)Agency overviewHeadquarters3132 Channel Drive, P.O. Box 112500, Juneau, Alaska 99811EmployeesOver 3,000 permanent full-time, part-time and non-permanent employees in 8 labor unions in 83 locations throughout the state.Agency executiveRyan Anderson, P.E., [1], CommissionerWebsitewww.dot.alaska.gov The Alaska Department of Transportation & Public ...

 

1985 film by Paul Verhoeven Flesh+BloodTheatrical release poster by Renato CasaroDirected byPaul VerhoevenScreenplay byGerard SoetemanPaul VerhoevenStory byGerard SoetemanProduced byGijs VersylusStarring Rutger Hauer Jennifer Jason Leigh Tom Burlinson Susan Tyrrell Ronald Lacey Jack Thompson CinematographyJan de BontEdited byIne SchenkkanMusic byBasil PoledourisProductioncompanies Riverside Pictures Impala Studios Distributed byOrion PicturesRelease datesJune 10, 1985 (1985-06-...

كلاكسار كلاك سر  - قرية -  تقسيم إداري البلد إيران  [1] الدولة  إيران المحافظة مازندران المقاطعة مقاطعة آمل الناحية الناحية المركزية القسم الريفي قسم بايين خيابان ليتكوة الريفي إحداثيات 36°29′46″N 52°20′38″E / 36.49611°N 52.34389°E / 36.49611; 52.34389 السكان التع...

 

Decline of classic Maya civilization This article is part of a series on theMaya civilization People Society Languages Writing Religion Mythology Sacrifice Cities Architecture Astronomy Calendar Stelae Art Textiles Trade Music Dance Medicine Cuisine Warfare History Preclassic Maya Classic Maya collapse Spanish conquest of the Maya Yucatán Chiapas Guatemala Petén  Mesoamerica portalvte In archaeology, the classic Maya collapse is the decline of the Classic Maya civilization and the ...

 

  لمعانٍ أخرى، طالع صمود الرجل الأخير (توضيح).هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أكتوبر 2021) صمود الرجل الاخيرLast Man Standing (بالإنجليزية) معلومات عامةالصنف الفني فيلم أكشن[1][2] — فيلم جريمة — في...

Japanese sculptor and manga artist Megumi IgarashiBorn (1972-03-14) 14 March 1972 (age 51)Other namesRokudenashiko (Japanese: ろくでなし子 / 碌でなし子 Little Reprobate)Occupation(s)Japanese sculptor and Manga artistKnown forUsing her vulva in works of artNotable workDeco Man, a series of decorated vulva moldsMan-Boat, kayak modeled on a 3D scan of her own vulva Megumi Igarashi (五十嵐恵, Igarashi Megumi, born 1972), who uses the pseudonym Rokudenashiko (ろく...

 

Avenue Henri Martín Andenes de la Estación Estación de la Avenida Henri MartinEstación de la Avenida Henri Martin (París)UbicaciónCoordenadas 48°51′51″N 2°16′19″E / 48.86417, 2.27194Comuna XVI DistritoLocalidad ParísZona 1Datos de la estaciónAltitud 46 metrosCódigo 87381046Inauguración 25 de septiembre de 1988N.º de andenes 1N.º de vías 2Propietario SNCF / RFFOperador SNCFLíneas Estación de la Avenida Foch ← → Estación de Boulainvilliers [edi...

 

Marine Geology redirects here. For the scientific journal, see Marine Geology (journal). Study of the history and structure of the ocean floor Oceanic crust is formed at an oceanic ridge, while the lithosphere is subducted back into the asthenosphere at trenches. Marine geology or geological oceanography is the study of the history and structure of the ocean floor. It involves geophysical, geochemical, sedimentological and paleontological investigations of the ocean floor and coastal zone. Ma...

Ganoderol Ganoderol A (top) and ganoderol B Identifiers CAS Number (A): 104700-97-2(B): 104700-96-1 3D model (JSmol) (A): Interactive image(B): Interactive image ChEBI (B): CHEBI:142261 ChEMBL (B): ChEMBL240972 ChemSpider (A): 10404029(B): 10404030 PubChem CID (A): 146156323(B): 13934286 InChI (A): InChI=1S/C30H46O2/c1-20(19-31)9-8-10-21(2)22-13-17-30(7)24-11-12-25-27(3,4)26(32)15-16-28(25,5)23(24)14-18-29(22,30)6/h9,11,14,21-22,25,31H,8,...

 

Artikel ini membutuhkan rujukan tambahan agar kualitasnya dapat dipastikan. Mohon bantu kami mengembangkan artikel ini dengan cara menambahkan rujukan ke sumber tepercaya. Pernyataan tak bersumber bisa saja dipertentangkan dan dihapus.Cari sumber: Limfosit – berita · surat kabar · buku · cendekiawan · JSTOR LimfositGambar Transmisi mikroskop electron Limfosit manusia.RincianSistemSistem imunFungsiSel darah putihPengidentifikasiBahasa Latinlymphocytes b...

 

Иктидомисы Тринадцатиполосый суслик (Ictidomys tridecemlineatus) Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКла...

Vide etiam paginam discretivam: Marcus Antonius (discretiva) Marcus Antonius (Musea Vaticana) Denarius argenteus anni 32 a.C.n.obverso Cleopatra: CLEOPA[TRAE•REGINAE•REGVM•]FILIORVM•REGVM•reverso Antonius: ANTONI•ARMENIA•DEVICTA Marcus Antonius (Romae natus die 14 Ianuarii 83 a.C.n.; Alexandriae mortuus die 1 Augusti 30 a.C.n.), filius Marci Antonii Cretici et nepos Marci Antonii Oratoris, magistratus et imperator Romanus fuit. Suffragator magnus C. Iulii Caesaris erat. Caesare...

 

Raisoam jinshar er ny hroggal Lus Euphorbia cur magh raisoamyn Ayns lus-oaylleeaght, she gass lus eh raisoam (ass Greagish ῥίζωμα, rhízōma dhossan dy 'raueyn,[1], ass ῥιζόω, rhizóō cur er goaill ynnyd)[2]. T'ad co-chruinnaghagh as fo-halloo son y chooid smoo, as t'ad cur magh fraueyn as stholeyn ass ny noadyn oc dy mennick. T'eh ny haase gientyn neucheintyssagh lossreeyn. Ta sthollane casley rish raisoam, agh ta sthollane gobbey ass gass t'ayn hannah, ta eddyr...

 

  Santanadactylus Rango temporal: 112 Ma PreЄ Є O S D C P T J K Pg N ↓ Cretácico Inferior Réplica del fósil de S. pricei (arriba).TaxonomíaReino: AnimaliaFilo: ChordataClase: SauropsidaOrden: PterosauriaSuborden: PterodactyloideaFamilia: InciertaGénero: SantanadactylusDe Buisonjé, 1980Especies S. brasilensis (especie tipo) ?S. pricei Wellnhofer, 1985 ?S. spixi Wellnhofer, 1985 [editar datos en Wikidata] Santanadactylus (nombre que significa dedo de la formación S...

国際民間航空条約 通称・略称 シカゴ条約ICAO条約署名 1944年12月7日署名場所 アメリカ合衆国・シカゴ発効 1947年4月4日寄託者 アメリカ合衆国連邦政府文献情報 昭和28年10月8日官報第8029号条約第21号言語 英語、フランス語、スペイン語、ロシア語主な内容 国際民間航空が安全にかつ整然と発達、また、国際航空運送業務が機会均等主義に基いて確立されて健全かつ経済的...

 

Ancient lake, Rift lake in Lanao del SurLake LanaoSentinel-2 photoLake LanaoLocation within the PhilippinesShow map of MindanaoLake LanaoLake Lanao (Philippines)Show map of PhilippinesLake Lanao-Agus River watershed mapLocationLanao del SurCoordinates07°52′48″N 124°15′09″E / 7.88000°N 124.25250°E / 7.88000; 124.25250Lake typeAncient lake, Rift lakePrimary inflows4 tributariesPrimary outflowsAgus RiverCatchment area1,678 km2 (648 sq mi) [...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!