Skip to content

Commit

Permalink
Cache span field buffers
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Saveau <[email protected]>
  • Loading branch information
SUPERCILEX authored and nagisa committed Jan 1, 2024
1 parent 7239d66 commit 47fea20
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions tracing-tracy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
#![doc = include_str!("../FEATURES.mkd")]
#![cfg_attr(tracing_tracy_docs, feature(doc_auto_cfg))]

use std::{borrow::Cow, cell::UnsafeCell, collections::VecDeque, fmt::Write};
use std::{borrow::Cow, cell::UnsafeCell, collections::VecDeque, fmt::Write, mem};
use tracing_core::{
field::{Field, Visit},
span::{Attributes, Id, Record},
Expand Down Expand Up @@ -164,6 +164,10 @@ impl Default for TracyLayer {
}
}

thread_local! {
static CACHE: VecCell<String> = const { VecCell::new() };
}

impl<S, F> Layer<S> for TracyLayer<F>
where
S: Subscriber + for<'a> registry::LookupSpan<'a>,
Expand All @@ -174,7 +178,8 @@ where

let mut extensions = span.extensions_mut();
if extensions.get_mut::<FormattedFields<F>>().is_none() {
let mut fields = FormattedFields::<F>::new(String::with_capacity(64));
let mut fields =
FormattedFields::<F>::new(CACHE.with(|cache| cache.pop().unwrap_or_default()));
if self.fmt.format_fields(fields.as_writer(), attrs).is_ok() {
extensions.insert(fields);
}
Expand All @@ -188,18 +193,15 @@ where
if let Some(fields) = extensions.get_mut::<FormattedFields<F>>() {
let _ = self.fmt.add_fields(fields, values);
} else {
let mut fields = FormattedFields::<F>::new(String::with_capacity(64));
let mut fields =
FormattedFields::<F>::new(CACHE.with(|cache| cache.pop().unwrap_or_default()));
if self.fmt.format_fields(fields.as_writer(), values).is_ok() {
extensions.insert(fields);
}
}
}

fn on_event(&self, event: &Event, _: Context<'_, S>) {
thread_local! {
static CACHE: VecCell<String> = const { VecCell::new() };
}

CACHE.with(|cache| {
let mut buf = cache.pop().unwrap_or_default();
let mut visitor = TracyEventFieldVisitor {
Expand Down Expand Up @@ -290,6 +292,18 @@ where
);
}
}

fn on_close(&self, id: Id, ctx: Context<'_, S>) {
let Some(span_data) = ctx.span(&id) else {
return;
};

if let Some(fields) = span_data.extensions_mut().get_mut::<FormattedFields<F>>() {
let mut buf = mem::take(&mut fields.fields);
buf.clear();
CACHE.with(|cache| cache.push(buf));
};
}
}

struct TracyEventFieldVisitor<'a> {
Expand Down

0 comments on commit 47fea20

Please sign in to comment.