Skip to content

Commit 6e6c858

Browse files
committed
[turbopack] optimize the TurboMalloc threadlocals
By declaring our initializer as `const {..}` we can leverage the experimental `#[thread_local]` attribute which delgates to `llvms` `threadlocal` implementation. This can improve performance on supported platforms.
1 parent 660df3c commit 6e6c858

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

turbopack/crates/turbo-tasks-malloc/src/counter.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ use std::{
66

77
use crate::AllocationCounters;
88

9+
/// Tracks the current total amount of memory allocated through all the [ThreadLocalCounter]
10+
/// instances. This is an overestimate as individual threads 'preallocate' a [TARGET_BUFFER] bytes
11+
/// to reduce the number of global synchronizations. This means at any given time this might
12+
/// overcount by up to [MAX_BUFFER] bytes for each thread.
913
static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
1014
const KB: usize = 1024;
1115
/// When global counter is updates we will keep a thread-local buffer of this
@@ -26,6 +30,12 @@ struct ThreadLocalCounter {
2630
}
2731

2832
impl ThreadLocalCounter {
33+
const fn new() -> Self {
34+
Self {
35+
buffer: 0,
36+
allocation_counters: AllocationCounters::new(),
37+
}
38+
}
2939
fn add(&mut self, size: usize) {
3040
self.allocation_counters.allocations += size;
3141
self.allocation_counters.allocation_count += 1;
@@ -88,7 +98,7 @@ impl ThreadLocalCounter {
8898
}
8999

90100
thread_local! {
91-
static LOCAL_COUNTER: UnsafeCell<ThreadLocalCounter> = UnsafeCell::new(ThreadLocalCounter::default());
101+
static LOCAL_COUNTER: UnsafeCell<ThreadLocalCounter> = const {UnsafeCell::new(ThreadLocalCounter::new())};
92102
}
93103

94104
pub fn get() -> usize {

turbopack/crates/turbo-tasks-malloc/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,15 @@ pub struct AllocationCounters {
3434
}
3535

3636
impl AllocationCounters {
37+
const fn new() -> Self {
38+
Self {
39+
allocation_count: 0,
40+
deallocation_count: 0,
41+
allocations: 0,
42+
deallocations: 0,
43+
_not_send: PhantomData {},
44+
}
45+
}
3746
pub fn until_now(&self) -> AllocationInfo {
3847
let new = TurboMalloc::allocation_counters();
3948
AllocationInfo {
@@ -50,6 +59,7 @@ impl AllocationCounters {
5059
pub struct TurboMalloc;
5160

5261
impl TurboMalloc {
62+
// Returns the current amount of memory
5363
pub fn memory_usage() -> usize {
5464
get()
5565
}

0 commit comments

Comments
 (0)