@@ -329,6 +329,8 @@ fn env_on_isolate_unwrap(isolate: &mut Isolate) -> &mut JsInstanceEnv {
329329struct JsInstanceEnv {
330330 instance_env : InstanceEnv ,
331331 module_def : Option < Arc < ModuleDef > > ,
332+ /// Last used-heap sample captured by the worker's periodic heap checks.
333+ cached_used_heap_size : usize ,
332334
333335 /// The slab of `BufferIters` created for this instance.
334336 iters : RowIters ,
@@ -353,6 +355,7 @@ impl JsInstanceEnv {
353355 Self {
354356 instance_env,
355357 module_def : None ,
358+ cached_used_heap_size : 0 ,
356359 call_times : CallTimes :: new ( ) ,
357360 iters : <_ >:: default ( ) ,
358361 chunk_pool : <_ >:: default ( ) ,
@@ -407,6 +410,16 @@ impl JsInstanceEnv {
407410 }
408411 }
409412
413+ /// Refresh the cached heap usage after an explicit V8 heap sample.
414+ fn set_cached_used_heap_size ( & mut self , bytes : usize ) {
415+ self . cached_used_heap_size = bytes;
416+ }
417+
418+ /// Return the last heap sample without forcing a fresh V8 query.
419+ fn cached_used_heap_size ( & self ) -> usize {
420+ self . cached_used_heap_size
421+ }
422+
410423 fn set_module_def ( & mut self , module_def : Arc < ModuleDef > ) {
411424 self . module_def = Some ( module_def) ;
412425 }
@@ -924,7 +937,10 @@ fn adjust_gauge(gauge: &IntGauge, delta: i64) {
924937}
925938
926939fn sample_heap_stats ( scope : & mut PinScope < ' _ , ' _ > , metrics : & mut V8HeapMetrics ) -> v8:: HeapStatistics {
940+ // Whenever we sample heap statistics, we cache them on the isolate so that
941+ // the per-call execution stats can avoid querying them on each invocation.
927942 let stats = scope. get_heap_statistics ( ) ;
943+ env_on_isolate_unwrap ( scope) . set_cached_used_heap_size ( stats. used_heap_size ( ) ) ;
928944 metrics. observe ( & stats) ;
929945 stats
930946}
@@ -1788,9 +1804,8 @@ where
17881804 // Derive energy stats.
17891805 let energy = energy_from_elapsed ( budget, timings. total_duration ) ;
17901806
1791- // Fetch the currently used heap size in V8.
1792- // The used size is ostensibly fairer than the total size.
1793- let memory_allocation = scope. get_heap_statistics ( ) . used_heap_size ( ) ;
1807+ // Reuse the last periodic heap sample instead of querying V8 on every call.
1808+ let memory_allocation = env_on_isolate_unwrap ( scope) . cached_used_heap_size ( ) ;
17941809
17951810 let stats = ExecutionStats {
17961811 energy,
0 commit comments