Caché de Resultados
En esta página
@memoize almacena el resultado de cada combinación de argumentos de forma
permanente. Es ideal para funciones puras y costosas cuyos argumentos se repiten
— como recursión exponencial o búsquedas lentas:
Caché vitalicio por argumentos; fibonacci(30) se vuelve instantáneo.
// Feature: `@memoize` — automatic cache by arguments
// Syntax: `@memoize` before the `fn`. Cache lives for the lifetime of the program.
// When to use: pure, expensive functions (exponential recursion, parsing,
// lookups) where the same arguments repeat.
@memoize
fn fibonacci(n: int) -> int {
if n <= 1 { return n }
return fibonacci(n - 1) + fibonacci(n - 2)
}
// fib(30) would be slow without cache; with memoize it is instant.
print("fib(10) = {fibonacci(10)}")
// expected: fib(10) = 55
print("fib(20) = {fibonacci(20)}")
// expected: fib(20) = 6765
print("fib(30) = {fibonacci(30)}")
// expected: fib(30) = 832040
// Memoize also works with multiple arguments.
@memoize
fn pow(base: int, exp: int) -> int {
if exp == 0 { return 1 }
return base * pow(base, exp - 1)
}
print("2^10 = {pow(2, 10)}")
// expected: 2^10 = 1024
print("3^5 = {pow(3, 5)}")
// expected: 3^5 = 243
Cuando los datos tienen una validez limitada, usa @cached(ttl) indicando el
tiempo de vida en segundos. Tras el TTL la función se re-ejecuta; entre llamadas,
el resultado almacenado se devuelve sin coste adicional:
Caché con expiración: TTL corto para cálculos, TTL largo para configuraciones.
// Feature: `@cached(ttl)` — memoize with expiration
// Syntax: `@cached(<seconds>)`. After the TTL, the call is re-executed.
// When to use: data that is "fresh" within a window (price, quote,
// API response, remote configuration).
@cached(60)
fn expensive_calc(x: int) -> int {
print(" computing cube({x})")
return x * x * x
}
print("cube(5) = {expensive_calc(5)}") // prints "computing"
print("cube(5) = {expensive_calc(5)}") // cached, no "computing"
print("cube(7) = {expensive_calc(7)}") // new argument -> re-executes
print("cube(7) = {expensive_calc(7)}") // cached
// expected:
// computing cube(5)
// cube(5) = 125
// cube(5) = 125
// computing cube(7)
// cube(7) = 343
// cube(7) = 343
// Long TTL simulates "config loaded once".
@cached(3600)
fn load_config() -> str {
print(" loading config")
return "host=localhost;port=8080"
}
print(load_config())
print(load_config())
// expected:
// loading config
// host=localhost;port=8080
// host=localhost;port=8080
Desafío
Cambia el TTL de expensive_calc a 1 y llámala dos veces con el mismo
argumento en rápida sucesión. ¿Qué ocurre? Añade un @log para confirmar
cuántas veces el cuerpo se ejecuta realmente.
Consulta también