Memory Management
Values like numbers, strings, lists, and maps are freed on their own when nothing uses them. Objects are different: an object is part of the document, and it stays there until something removes it, even if no field points to it anymore. For a document that runs once and is thrown away, that doesn't matter. For one that lives a long time, like a policy that runs on every request, temporary objects add up.
Temporary Objects with using
Declare a temporary object with using instead of const, and it's dropped automatically when its block or function ends, however it ends: normally, with return, with break, or with an error:
orders: {}
fn check(total: float) -> bool {
using order = new { total: total, tax: total * 0.2 } on self.orders;
order.total + order.tax < 1000
}
#[main]
fn main() {
pln(self.check(500));
pln(self.check(900));
pln(self.orders.children().len()); // 0: both were dropped
}For a temporary object you pass straight into a call, put using in front of new. It's dropped when the enclosing block or function ends:
self.handle(using new { id: 42, kind: 'refund' });
Don't return a using object, since it's dropped as the function returns. And when you don't need an object at all, a map is simpler: {'id': 42}.
drop
drop(obj) removes an object, and everything inside it, right away. If its type has a #[dropped] function, that runs first:
#[type]
Session: {
str user: ''
#[dropped]
fn closed() {
pln(`session for ${self.user} closed`);
}
}
#[main]
fn main() {
const session = new Session { user: 'ada' };
drop(session);
pln(session.exists());
}A using object runs its #[dropped] function too.
Removing Fields
obj.remove('name') removes a field. If the field holds an object, the object stays in the document unless you pass shallow = false:
cache: {
a: { value: 1 }
b: { value: 2 }
}
#[main]
fn main() {
self.cache.remove('a', shallow = false); // the field and its object
pln(self.cache.children().len());
}Many Temporaries at Once
When a task creates lots of objects, possibly deep inside other functions, create them all on one scratch object and drop that. A plain block with using makes a tidy scope for it:
fn line(item: str, price: float, scratch: obj) -> obj {
new { item: item, price: price } on scratch
}
#[main]
fn main() {
let total = 0;
{
using scratch = new {};
const lines = [
self.line('seat', 20, scratch),
self.line('storage', 5, scratch),
];
for (const line in lines) total += line.price;
pln(scratch.children().len());
}
pln(total);
}Everything created on scratch goes when scratch does.
Finding Leaks
stof test --leaks runs each test on its own and fails any test that leaves objects behind, saying where they are:
leaked: root @ build_order ... 1 object never dropped
1 on root (drop it, or declare it with `using`)
It's worth running on documents that stay in memory or get exported as binary Stof, since bstf includes every object still in the document. Next, Units Reference.