Lazy Objects
State initializes on first touch — PHP 8.4 lazy ghosts and proxies against deferred initialization in 10 languages.
C C23
#include <stdio.h>
/* C has no lazy objects: a flag plus an init check inside every accessor
is the idiom, and nothing enforces that the check was written */
typedef struct {
const char *lang;
int initialized;
} Config;
static Config g_config = {NULL, 0};
static const char *config_lang(void) {
if (!g_config.initialized) {
printf(" [init runs]\n");
g_config.lang = "c";
g_config.initialized = 1;
}
return g_config.lang;
}
int main(void) {
printf("created, init not yet run\n");
printf("%s\n", config_lang());
printf("%s\n", config_lang());
return 0;
}
created, init not yet run [init runs] c c
C++ C++26
#include <cstdio>
#include <string>
struct Config {
std::string lang;
};
// Meyers singleton: the function-local static is initialized on first
// call, exactly once, thread-safe since C++11 — the C++ lazy idiom
Config &config() {
static Config instance = [] {
std::printf(" [init runs]\n");
return Config{"cpp"};
}();
return instance;
}
int main() {
std::printf("created, init not yet run\n");
std::printf("%s\n", config().lang.c_str());
std::printf("%s\n", config().lang.c_str());
}
created, init not yet run [init runs] cpp cpp
C# v11.0.100
var cfg = new Lazy<string>(() => {
Console.WriteLine(" [factory runs]");
return "csharp";
});
Console.WriteLine("created, factory not yet run");
Console.WriteLine(cfg.Value); // the factory runs here, once
Console.WriteLine(cfg.Value); // cached afterwards
created, factory not yet run [factory runs] csharp csharp
Go v1.27.4
package main
import (
"fmt"
"sync"
)
// sync.OnceValue computes on first call and caches: the Go lazy idiom
var config = sync.OnceValue(func() string {
fmt.Println(" [init runs]")
return "go"
})
func main() {
fmt.Println("created, init not yet run")
fmt.Println(config())
fmt.Println(config())
}
created, init not yet run [init runs] go go
Java v27.0.1
public class Main {
static String cfg = null;
// hand-rolled memoization: the check-then-init dance (synchronized for
// thread safety) — Java ships no language-level lazy object
static synchronized String config() {
if (cfg == null) {
System.out.println(" [init runs]");
cfg = "java";
}
return cfg;
}
public static void main(String[] args) {
System.out.println("created, init not yet run");
System.out.println(config());
System.out.println(config());
}
}
created, init not yet run [init runs] java java
JavaScript v26.13.1
function lazyConfig(factory) {
let real;
let count = 0;
return {
get value() {
if (real === undefined) {
count++;
real = factory(); // computed once, then cached
}
return real;
},
get initCount() { return count; },
};
}
const cfg = lazyConfig(() => {
console.log(" [factory runs]");
return "javascript";
});
console.log("created, factory not yet run");
console.log(cfg.value);
console.log(cfg.value);
console.log("init count:", cfg.initCount);
created, factory not yet run [factory runs] javascript javascript init count: 1
PHP v8.6.0
class Config {
public function __construct(public array $data) {
echo " [构造器执行]\n";
}
}
$initCount = 0;
// PHP 8.4 lazy ghost: the object exists but its constructor has not run;
// the initializer fires automatically on first state access
$ref = new ReflectionClass(Config::class);
$cfg = $ref->newLazyGhost(function (Config $obj) use (&$initCount) {
$initCount++;
$obj->__construct(['lang' => 'php', 'version' => '8.4']);
});
echo "对象已创建,构造器尚未执行\n";
echo $cfg->data['lang'], "\n"; // first access: triggers initialization
echo $cfg->data['version'], "\n"; // already initialized: fires no more
echo "初始化次数: $initCount\n";
对象已创建,构造器尚未执行 [构造器执行] php 8.4 初始化次数: 1
Python v3.15.2
class Config:
def __init__(self):
self._data = None
self.init_count = 0
@property
def data(self):
if self._data is None: # hand-rolled lazy init
self.init_count += 1
print(" [init runs]")
self._data = {"lang": "python"}
return self._data
cfg = Config()
print("created, init not yet run")
print(cfg.data["lang"])
print(cfg.data["lang"])
print("init count:", cfg.init_count)
created, init not yet run [init runs] python python init count: 1
Rust v1.99.1
use std::sync::OnceLock;
// OnceLock computes on first access and caches forever: the std-lib lazy
// idiom (the value behaves like a plain one once initialized)
static CONFIG: OnceLock<&'static str> = OnceLock::new();
fn config() -> &'static str {
CONFIG.get_or_init(|| {
println!(" [init runs]");
"rust"
})
}
fn main() {
println!("created, init not yet run");
println!("{}", config());
println!("{}", config());
}
created, init not yet run [init runs] rust rust
TypeScript v26.13.1
function lazyConfig(factory: () => string) {
let real: string | undefined;
let count = 0;
return {
get value(): string {
if (real === undefined) {
count++;
real = factory(); // computed once, then cached
}
return real;
},
get initCount(): number { return count; },
};
}
const cfg = lazyConfig(() => {
console.log(" [factory runs]");
return "typescript";
});
console.log("created, factory not yet run");
console.log(cfg.value);
console.log(cfg.value);
console.log("init count:", cfg.initCount);
created, factory not yet run [factory runs] typescript typescript init count: 1
Language differences
C: no lazy objects (example): a flag plus an if-check inside every accessor is the only idiom; whether the check was written rests on discipline, with a separate lock for thread safety; opaque pointers plus init functions repeat the same pattern in library design.
C++: the Meyers singleton (example): a function-local static is initialized exactly once on first call, thread-safe since C++11 by compiler guarantee; the limits are function-level granularity and lifetime-to-program-end — no transparent mechanism for an object that exists first and initializes later; std::call_once offers the more general once semantics.
C#: Lazy<T> (example): a typed lazy wrapper whose .Value fires the factory on first access and caches forever, with configurable thread-safety modes; semantically the closest to PHP's lazy proxy — both hold a factory and run it on first touch. The difference: C# wraps in a type (cfg.Value, not cfg), while PHP's ghost is fully transparent to callers, indistinguishable from a normal object.
Go: sync.OnceValue / sync.Once (example): first call computes and caches (OnceValue is the 1.21+ value-shaped idiom); granularity is function-level and access is an explicit call — no transparency of field access triggering initialization.
Java: no language-level support (example): hand-rolled check-then-init (synchronized, or volatile plus double-checked locking); the class-loading mechanism is itself lazy (a class loads and runs its static initializers on first use) but that is class-level, not object-level; Supplier plus memoization is a library pattern (Guava's Suppliers.memoize, non-standard).
JavaScript: Proxy/getter caching (example): hand-written lazy getters are the most common; Proxy can intercept any property access for a transparent proxy (Vue's reactivity walks this road), but the language has no built-in object that exists first with its constructor deferred; top-level await (ESM) provides module-level laziness.
PHP: 8.4+ lazy objects (example): two strategies — newLazyGhost (the ghost: the original object initializes in place and is indistinguishable from a normal one afterwards) and newLazyProxy (the proxy: a factory returns the real instance and property access forwards to it); the initializer fires automatically exactly once on first state access (the example asserts the init count is 1); reading properties, isset, foreach, serialize, and clone all trigger; calling methods without touching state does not; if the initializer throws, the object rolls back to lazy; ORMs and DI containers are the primary use cases.
Python: hand-rolled @property caching (example): the None sentinel plus fill-on-first-read is the standard dance; functools.cached_property is the ready-made library answer (computes on first access and writes back into the instance __dict__); a module-level lru_cache-decorated factory is another road; no transparent lazy objects in the language itself.
Rust: OnceLock / once_cell::Lazy (example): OnceLock::get_or_init initializes on first access and the type system guarantees exactly once (the example's single [init runs] line is the type-level assertion); once_cell::Lazy moves the syntax closer to a lazy static value; granularity is value-level with access through a function — no object-level constructor deferral.
TypeScript: at the language level the same as JS (example): getter caching and Proxy alike; the type system can model lazy containers (a Lazy<T> generic class), but that is type gymnastics rather than a runtime mechanism; experimental decorators can hang lazy logic on properties, kin to Python's @property in spirit.