Unverified Commit d5177699 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[Turbopack] avoid some allocations (#75285)

### What?

* more memory efficient AggregationUpdateQueue by using SmallVec and
boxing some job types
* avoid allocation in CaptureFuture by avoiding the Arc and the Mutex
and using a thread local reference
parent 7578b8fe
......@@ -2,6 +2,7 @@ use std::mem::take;
use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use turbo_tasks::TaskId;
#[cfg(feature = "trace_task_dirty")]
......@@ -12,7 +13,7 @@ use crate::{
operation::{
aggregation_update::{
get_aggregation_number, get_uppers, is_aggregating_node, AggregationUpdateJob,
AggregationUpdateQueue,
AggregationUpdateQueue, InnerOfUppersLostFollowersJob,
},
invalidate::make_task_dirty,
AggregatedDataUpdate, ExecuteContext, Operation, TaskGuard,
......@@ -77,7 +78,7 @@ impl Operation for CleanupOldEdgesOperation {
if let Some(edge) = outdated.pop() {
match edge {
OutdatedEdge::Child(child_id) => {
let mut children = Vec::new();
let mut children = SmallVec::new();
children.push(child_id);
outdated.retain(|e| match e {
OutdatedEdge::Child(id) => {
......@@ -104,10 +105,13 @@ impl Operation for CleanupOldEdgesOperation {
task_ids: children.clone(),
});
}
queue.push(AggregationUpdateJob::InnerOfUppersLostFollowers {
upper_ids,
lost_follower_ids: children,
});
queue.push(
InnerOfUppersLostFollowersJob {
upper_ids,
lost_follower_ids: children,
}
.into(),
);
}
}
OutdatedEdge::Collectible(collectible, count) => {
......
#![feature(anonymous_lifetime_in_impl_trait)]
#![feature(associated_type_defaults)]
#![feature(iter_collect_into)]
#![feature(box_patterns)]
mod backend;
mod backing_storage;
......
use std::{
cell::RefCell,
future::Future,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
time::{Duration, Instant},
};
use pin_project_lite::pin_project;
use tokio::{task::futures::TaskLocalFuture, task_local};
use turbo_tasks_malloc::{AllocationInfo, TurboMalloc};
task_local! {
static EXTRA: Arc<Mutex<(Duration, usize, usize)>>;
struct ThreadLocalData {
duration: Duration,
allocations: usize,
deallocations: usize,
}
thread_local! {
static EXTRA: RefCell<Option<*mut ThreadLocalData>> = const { RefCell::new(None) };
}
pin_project! {
pub struct CaptureFuture<T, F: Future<Output = T>> {
cell: Arc<Mutex<(Duration, usize, usize)>>,
#[pin]
future: TaskLocalFuture<Arc<Mutex<(Duration, usize, usize)>>, F>,
future: F,
duration: Duration,
allocations: usize,
deallocations: usize,
......@@ -27,10 +31,8 @@ pin_project! {
impl<T, F: Future<Output = T>> CaptureFuture<T, F> {
pub fn new(future: F) -> Self {
let cell = Arc::new(Mutex::new((Duration::ZERO, 0, 0)));
Self {
future: EXTRA.scope(cell.clone(), future),
cell,
future,
duration: Duration::ZERO,
allocations: 0,
deallocations: 0,
......@@ -38,15 +40,27 @@ impl<T, F: Future<Output = T>> CaptureFuture<T, F> {
}
}
fn try_with_thread_local_data(f: impl FnOnce(&mut ThreadLocalData)) {
EXTRA.with_borrow(|cell| {
if let Some(data) = cell {
// Safety: This data is thread local and only accessed in this thread
unsafe {
f(&mut **data);
}
}
});
}
pub fn add_duration(duration: Duration) {
let _ = EXTRA.try_with(|cell| cell.lock().unwrap().0 += duration);
try_with_thread_local_data(|data| {
data.duration += duration;
});
}
pub fn add_allocation_info(alloc_info: AllocationInfo) {
let _ = EXTRA.try_with(|cell| {
let mut guard = cell.lock().unwrap();
guard.1 += alloc_info.allocations;
guard.2 += alloc_info.deallocations;
try_with_thread_local_data(|data| {
data.allocations += alloc_info.allocations;
data.deallocations += alloc_info.deallocations;
});
}
......@@ -57,20 +71,38 @@ impl<T, F: Future<Output = T>> Future for CaptureFuture<T, F> {
let this = self.project();
let start = Instant::now();
let start_allocations = TurboMalloc::allocation_counters();
let guard = ThreadLocalDataDropGuard;
let mut data = ThreadLocalData {
duration: Duration::ZERO,
allocations: 0,
deallocations: 0,
};
EXTRA.with_borrow_mut(|cell| {
*cell = Some(&mut data as *mut ThreadLocalData);
});
let result = this.future.poll(cx);
drop(guard);
let elapsed = start.elapsed();
let allocations = start_allocations.until_now();
*this.duration += elapsed;
*this.allocations += allocations.allocations;
*this.deallocations += allocations.deallocations;
*this.duration += elapsed + data.duration;
*this.allocations += allocations.allocations + data.allocations;
*this.deallocations += allocations.deallocations + data.deallocations;
match result {
Poll::Ready(r) => {
let (duration, allocations, deallocations) = *this.cell.lock().unwrap();
let memory_usage = (*this.allocations + allocations)
.saturating_sub(*this.deallocations + deallocations);
Poll::Ready((r, *this.duration + duration, memory_usage))
let memory_usage = this.allocations.saturating_sub(*this.deallocations);
Poll::Ready((r, *this.duration, memory_usage))
}
Poll::Pending => Poll::Pending,
}
}
}
struct ThreadLocalDataDropGuard;
impl Drop for ThreadLocalDataDropGuard {
fn drop(&mut self) {
EXTRA.with_borrow_mut(|cell| {
*cell = None;
});
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment