Skip to content

Commit 322cd2d

Browse files
committed
perf(rust): the object heap in fixed chunks, and arenas that move rather than realloc
macOS does not reuse a large block that realloc grew once it is freed (20 lines of plain Rust show it), so a process running one large program after another kept every heap it ever grew: a 200k-object program peaked at 498 MB after 12 runs in one process, where QuickJS holds 78 MB. Objects now live in chunks of 4,096 slots, each allocated whole; the first starts small for the many runs that make few. Cell and string arenas past 4,096 slots move to a new allocation of twice the size instead of growing in place, and smaller ones grow by a quarter. 12 runs in one process, peak RSS: 200k objects 498 to 77 MB, JSON round-trip 84 to 14 MB, 100k closures 114 to 30 MB. Cost: heap[id] is two indexed loads, 1 to 5% more instructions on the bench programs. Array elements and Map entries are still vectors realloc grows.
1 parent 97d4afe commit 322cd2d

4 files changed

Lines changed: 103 additions & 32 deletions

File tree

‎rust/crates/psychoscript/src/builtins/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ impl Vm {
389389

390390
/// Makes the fresh runtime's built-ins, unless the VM was made with them (`Vm::new` from the image).
391391
pub fn setup(&mut self) {
392-
if !self.heap.is_empty() {
392+
if self.heap.len() != 0 {
393393
return;
394394
}
395395
let object_proto = self.alloc(Obj::new(None, Kind::Ordinary));

‎rust/crates/psychoscript/src/collector.rs‎

Lines changed: 96 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
3737
use std::borrow::Cow;
3838
use std::ops::{Deref, DerefMut, Index, IndexMut};
39-
use std::slice::SliceIndex;
4039

4140
use crate::object::{Kind, Obj};
4241
use crate::reach::Ref;
@@ -87,14 +86,44 @@ fn stress() -> bool {
8786
*ON.get_or_init(|| std::env::var_os("PSYCHOSCRIPT_GC_STRESS").is_some_and(|v| v == "1"))
8887
}
8988

89+
/// Objects to a chunk of the heap: 4,096 of them are 256 KiB.
90+
const HEAP_CHUNK_BITS: u32 = 12;
91+
const HEAP_CHUNK: usize = 1 << HEAP_CHUNK_BITS;
92+
const HEAP_CHUNK_MASK: usize = HEAP_CHUNK - 1;
93+
94+
/// From this many slots on, a full arena moves to a new allocation instead of growing in place.
95+
const ARENA_MOVE_FROM: usize = 4096;
96+
97+
/// Makes room in a full arena (cells, strings) for more slots. A large one moves to a new allocation of twice the
98+
/// size rather than growing in place: macOS does not reuse a large block that `realloc` grew once it is freed, so a
99+
/// process running one large program after another would keep every arena it ever grew.
100+
#[cold]
101+
#[inline(never)]
102+
pub(crate) fn grow_arena<T>(v: &mut Vec<T>) {
103+
let n = v.len();
104+
if n < ARENA_MOVE_FROM {
105+
// A small one grows in place by a quarter: doubled, a short program's would be half unused.
106+
return v.reserve_exact((n / 4).max(64));
107+
}
108+
let mut bigger = Vec::with_capacity(n * 2);
109+
bigger.append(v);
110+
*v = bigger;
111+
}
112+
90113
pub(crate) fn first_limit() -> usize {
91114
if stress() { 0 } else { FIRST }
92115
}
93116

94117
/// The run's objects. The first write to an object while marking traces it first: every `heap[id]` that may write
95118
/// goes through `IndexMut`.
96119
pub struct Heap {
97-
objs: Vec<Obj>,
120+
/// The objects, `CHUNK` to a chunk, every chunk but the last full: object `i` is `chunks[i >> HEAP_CHUNK_BITS][i &
121+
/// CHUNK_MASK]`. A chunk is allocated at its full size and never grows, except the first, which starts small for
122+
/// the many runs that make few objects. One vector for them all would grow with `realloc`, which leaves up to
123+
/// half of it unused, and macOS does not reuse a large block `realloc` grew once it is freed: a process running
124+
/// one large program after another kept every heap it ever grew.
125+
chunks: Vec<Vec<Obj>>,
126+
len: usize,
98127
pub(crate) marking: bool,
99128
marks: Marks,
100129
}
@@ -112,7 +141,8 @@ struct Marks {
112141
impl Heap {
113142
pub fn with_capacity(n: usize) -> Heap {
114143
Heap {
115-
objs: Vec::with_capacity(n),
144+
chunks: vec![Vec::with_capacity(n.min(HEAP_CHUNK))],
145+
len: 0,
116146
marking: false,
117147
marks: Marks::default(),
118148
}
@@ -121,7 +151,7 @@ impl Heap {
121151
/// A copy of a fresh runtime's heap, which holds only what `Obj::clone_base` copies, with room for a small
122152
/// program's own objects.
123153
pub(crate) fn clone_base(&self) -> Heap {
124-
let mut heap = Heap::with_capacity(self.len() + 34);
154+
let mut heap = Heap::with_capacity(self.len + 34);
125155
for o in self.iter() {
126156
heap.push(o.clone_base());
127157
}
@@ -132,23 +162,64 @@ impl Heap {
132162
/// changes nothing marking must see.
133163
#[inline(always)]
134164
pub(crate) fn bytes_of(&mut self, i: Id) -> Option<&mut Vec<u8>> {
135-
match &mut self.objs.get_mut(i as usize)?.kind {
165+
if i as usize >= self.len {
166+
return None;
167+
}
168+
match &mut self.slot_mut(i as usize).kind {
136169
Kind::Storage(data) => Some(data),
137170
_ => None,
138171
}
139172
}
140173

174+
#[inline(always)]
175+
pub fn len(&self) -> usize {
176+
self.len
177+
}
178+
179+
/// The objects in id order.
180+
pub fn iter(&self) -> impl Iterator<Item = &Obj> {
181+
self.chunks.iter().flatten()
182+
}
183+
184+
#[inline(always)]
185+
fn slot_mut(&mut self, i: usize) -> &mut Obj {
186+
&mut self.chunks[i >> HEAP_CHUNK_BITS][i & HEAP_CHUNK_MASK]
187+
}
188+
141189
#[inline(always)]
142190
pub fn push(&mut self, o: Obj) {
143-
self.objs.push(o);
191+
match self.chunks.last_mut() {
192+
Some(last) if last.len() < last.capacity() => last.push(o),
193+
_ => self.push_slow(o),
194+
}
195+
self.len += 1;
196+
}
197+
198+
/// `push` with the last chunk at its capacity: the first chunk doubles until it is whole, then each new chunk
199+
/// is allocated whole.
200+
#[cold]
201+
#[inline(never)]
202+
fn push_slow(&mut self, o: Obj) {
203+
match self.chunks.last_mut() {
204+
Some(last) if last.capacity() < HEAP_CHUNK => {
205+
let more = last.capacity().clamp(16, HEAP_CHUNK - last.capacity());
206+
last.reserve_exact(more);
207+
last.push(o);
208+
}
209+
_ => {
210+
let mut chunk = Vec::with_capacity(HEAP_CHUNK);
211+
chunk.push(o);
212+
self.chunks.push(chunk);
213+
}
214+
}
144215
}
145216

146217
/// Fills freed slot `i`, past the barrier: a reused slot is black or white already. The sweep left an empty
147218
/// object there, which owns no memory, so it is forgotten rather than dropped: that keeps drop code out of every
148219
/// `alloc`.
149220
#[inline(always)]
150221
pub(crate) fn put(&mut self, i: usize, o: Obj) {
151-
std::mem::forget(std::mem::replace(&mut self.objs[i], o));
222+
std::mem::forget(std::mem::replace(self.slot_mut(i), o));
152223
}
153224

154225
/// Traces object `i` as it is, before a write, unless it is black already.
@@ -161,33 +232,27 @@ impl Heap {
161232
}
162233
m.color[i] = BLACK;
163234
// Objects are greyed here; strings, cells and atoms wait for the next step.
164-
crate::reach::children(&self.objs[i], &mut |r| match r {
165-
Ref::Obj(id) => {
166-
if m.color.get(id as usize) == Some(&WHITE) {
167-
m.color[id as usize] = GREY;
168-
m.grey.push(id);
235+
crate::reach::children(
236+
&self.chunks[i >> HEAP_CHUNK_BITS][i & HEAP_CHUNK_MASK],
237+
&mut |r| match r {
238+
Ref::Obj(id) => {
239+
if m.color.get(id as usize) == Some(&WHITE) {
240+
m.color[id as usize] = GREY;
241+
m.grey.push(id);
242+
}
169243
}
170-
}
171-
_ => m.pending.push(r),
172-
});
173-
}
174-
}
175-
176-
impl Deref for Heap {
177-
type Target = Vec<Obj>;
178-
179-
#[inline(always)]
180-
fn deref(&self) -> &Vec<Obj> {
181-
&self.objs
244+
_ => m.pending.push(r),
245+
},
246+
);
182247
}
183248
}
184249

185-
impl<I: SliceIndex<[Obj]>> Index<I> for Heap {
186-
type Output = I::Output;
250+
impl Index<usize> for Heap {
251+
type Output = Obj;
187252

188253
#[inline(always)]
189-
fn index(&self, i: I) -> &I::Output {
190-
&self.objs[i]
254+
fn index(&self, i: usize) -> &Obj {
255+
&self.chunks[i >> HEAP_CHUNK_BITS][i & HEAP_CHUNK_MASK]
191256
}
192257
}
193258

@@ -197,7 +262,7 @@ impl IndexMut<usize> for Heap {
197262
if self.marking {
198263
self.barrier(i);
199264
}
200-
&mut self.objs[i]
265+
self.slot_mut(i)
201266
}
202267
}
203268

@@ -888,10 +953,10 @@ impl Vm {
888953
match self.heap.marks.color[at] {
889954
WHITE => {
890955
self.heap.marks.color[at] = FREE;
891-
if let Kind::BigInt(n) = &self.heap.objs[at].kind {
956+
if let Kind::BigInt(n) = &self.heap[at].kind {
892957
self.bigints.forget(at as Id, n);
893958
}
894-
self.heap.objs[at] = Obj::new(None, Kind::Ordinary);
959+
*self.heap.slot_mut(at) = Obj::new(None, Kind::Ordinary);
895960
self.gc.free.push(at as Id);
896961
work += FREE_WORK;
897962
}

‎rust/crates/psychoscript/src/strings.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,9 @@ impl Strings {
343343
std::mem::forget(std::mem::replace(&mut self.bufs[id as usize], entry));
344344
return id;
345345
}
346+
if self.bufs.len() == self.bufs.capacity() {
347+
crate::collector::grow_arena(&mut self.bufs);
348+
}
346349
self.bufs.push(entry);
347350
(self.bufs.len() - 1) as StrId
348351
}

‎rust/crates/psychoscript/src/vm.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,9 @@ impl Vm {
548548
if self.cells.len() >= self.gc.cell_limit {
549549
return self.gc_new_cell();
550550
}
551+
if self.cells.len() == self.cells.capacity() {
552+
crate::collector::grow_arena(&mut self.cells);
553+
}
551554
self.cells.push(Slot::UNINIT);
552555
self.cells.len() as u64 - 1
553556
}

0 commit comments

Comments
 (0)