Skip to content

Commit

Permalink
Reduce string allocations where possible (#506)
Browse files Browse the repository at this point in the history
  • Loading branch information
jtescher committed Mar 31, 2021
1 parent e169d8d commit a0b80e8
Show file tree
Hide file tree
Showing 17 changed files with 132 additions and 92 deletions.
2 changes: 1 addition & 1 deletion examples/async/src/main.rs
Expand Up @@ -46,7 +46,7 @@ async fn write(stream: &mut TcpStream) -> io::Result<usize> {

async fn run(addr: &SocketAddr) -> io::Result<usize> {
let tracer = global::tracer("runner");
let span = tracer.start(&format!("running: {}", addr));
let span = tracer.start(format!("running: {}", addr));
let cx = Context::current_with_span(span);

let mut stream = connect(addr).with_context(cx.clone()).await?;
Expand Down
7 changes: 3 additions & 4 deletions opentelemetry-datadog/src/exporter/model/mod.rs
Expand Up @@ -80,7 +80,6 @@ pub(crate) mod tests {
trace::{SpanContext, SpanId, SpanKind, StatusCode, TraceId, TraceState},
Key,
};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

fn get_traces() -> Vec<Vec<trace::SpanData>> {
Expand Down Expand Up @@ -110,15 +109,15 @@ pub(crate) mod tests {
span_context,
parent_span_id: SpanId::from_u64(parent_span_id),
span_kind: SpanKind::Client,
name: "resource".to_string(),
name: "resource".into(),
start_time,
end_time,
attributes,
message_events,
links,
status_code: StatusCode::Ok,
status_message: String::new(),
resource: Arc::new(sdk::Resource::default()),
status_message: "".into(),
resource: None,
instrumentation_lib: InstrumentationLibrary::new("component", None),
}
}
Expand Down
21 changes: 10 additions & 11 deletions opentelemetry-jaeger/src/exporter/mod.rs
Expand Up @@ -499,7 +499,7 @@ fn convert_otel_span_into_jaeger_span(
trace_id_high,
span_id: span.span_context.span_id().to_u64() as i64,
parent_span_id: span.parent_span_id.to_u64() as i64,
operation_name: span.name,
operation_name: span.name.into_owned(),
references: links_to_references(span.links),
flags: span.span_context.trace_flags() as i32,
start_time: span
Expand All @@ -520,7 +520,7 @@ fn convert_otel_span_into_jaeger_span(
None
},
span.status_code,
span.status_message,
span.status_message.into_owned(),
span.span_kind,
)),
logs: events_to_logs(span.message_events),
Expand All @@ -530,16 +530,15 @@ fn convert_otel_span_into_jaeger_span(
fn build_process_tags(
span_data: &trace::SpanData,
) -> Option<impl Iterator<Item = jaeger::Tag> + '_> {
if span_data.resource.is_empty() {
None
} else {
Some(
span_data
.resource
span_data
.resource
.as_ref()
.filter(|resource| !resource.is_empty())
.map(|resource| {
resource
.iter()
.map(|(k, v)| KeyValue::new(k.clone(), v.clone()).into()),
)
}
.map(|(k, v)| KeyValue::new(k.clone(), v.clone()).into())
})
}

fn build_span_tags(
Expand Down
41 changes: 27 additions & 14 deletions opentelemetry-otlp/src/transform/traces.rs
Expand Up @@ -60,7 +60,10 @@ mod tonic {
let span_kind: span::SpanKind = source_span.span_kind.into();
ResourceSpans {
resource: Some(Resource {
attributes: resource_attributes(&source_span.resource).0,
attributes: resource_attributes(
source_span.resource.as_ref().map(AsRef::as_ref),
)
.0,
dropped_attributes_count: 0,
}),
instrumentation_library_spans: vec![InstrumentationLibrarySpans {
Expand All @@ -86,7 +89,7 @@ mod tonic {
vec![]
}
},
name: source_span.name,
name: source_span.name.into_owned(),
kind: span_kind as i32,
start_time_unix_nano: to_nanos(source_span.start_time),
end_time_unix_nano: to_nanos(source_span.end_time),
Expand All @@ -107,7 +110,7 @@ mod tonic {
links: source_span.links.into_iter().map(Into::into).collect(),
status: Some(Status {
code: status::StatusCode::from(source_span.status_code).into(),
message: source_span.status_message,
message: source_span.status_message.into_owned(),
..Default::default()
}),
}],
Expand All @@ -116,11 +119,14 @@ mod tonic {
}
}

fn resource_attributes(resource: &sdk::Resource) -> Attributes {
fn resource_attributes(resource: Option<&sdk::Resource>) -> Attributes {
resource
.iter()
.map(|(k, v)| opentelemetry::KeyValue::new(k.clone(), v.clone()))
.collect::<Vec<_>>()
.map(|res| {
res.iter()
.map(|(k, v)| opentelemetry::KeyValue::new(k.clone(), v.clone()))
.collect::<Vec<_>>()
})
.unwrap_or_default()
.into()
}
}
Expand Down Expand Up @@ -186,7 +192,10 @@ mod grpcio {
fn from(source_span: SpanData) -> Self {
ResourceSpans {
resource: SingularPtrField::from(Some(Resource {
attributes: resource_attributes(&source_span.resource).0,
attributes: resource_attributes(
source_span.resource.as_ref().map(AsRef::as_ref),
)
.0,
dropped_attributes_count: 0,
..Default::default()
})),
Expand Down Expand Up @@ -214,7 +223,7 @@ mod grpcio {
vec![]
}
},
name: source_span.name,
name: source_span.name.into_owned(),
kind: source_span.span_kind.into(),
start_time_unix_nano: to_nanos(source_span.start_time),
end_time_unix_nano: to_nanos(source_span.end_time),
Expand All @@ -240,7 +249,7 @@ mod grpcio {
),
status: SingularPtrField::some(Status {
code: Status_StatusCode::from(source_span.status_code),
message: source_span.status_message,
message: source_span.status_message.into_owned(),
..Default::default()
}),
..Default::default()
Expand All @@ -253,11 +262,15 @@ mod grpcio {
}
}

fn resource_attributes(resource: &sdk::Resource) -> Attributes {
fn resource_attributes(resource: Option<&sdk::Resource>) -> Attributes {
resource
.iter()
.map(|(k, v)| opentelemetry::KeyValue::new(k.clone(), v.clone()))
.collect::<Vec<_>>()
.map(|resource| {
resource
.iter()
.map(|(k, v)| opentelemetry::KeyValue::new(k.clone(), v.clone()))
.collect::<Vec<_>>()
})
.unwrap_or_default()
.into()
}
}
2 changes: 1 addition & 1 deletion opentelemetry-stackdriver/src/lib.rs
Expand Up @@ -171,7 +171,7 @@ impl StackDriverExporter {
hex::encode(span.span_context.trace_id().to_u128().to_be_bytes()),
hex::encode(span.span_context.span_id().to_u64().to_be_bytes())
),
display_name: Some(to_truncate(span.name.clone())),
display_name: Some(to_truncate(span.name.into_owned())),
span_id: hex::encode(span.span_context.span_id().to_u64().to_be_bytes()),
parent_span_id: hex::encode(span.parent_span_id.to_u64().to_be_bytes()),
start_time: Some(span.start_time.into()),
Expand Down
7 changes: 5 additions & 2 deletions opentelemetry-zipkin/src/exporter/model/mod.rs
Expand Up @@ -71,7 +71,10 @@ pub(crate) fn into_zipkin_span(local_endpoint: Endpoint, span_data: trace::SpanD
);
if let Some(status_code) = from_statuscode_to_str(span_data.status_code) {
if status_code == "ERROR" {
tags.insert(OTEL_ERROR_DESCRIPTION.into(), span_data.status_message);
tags.insert(
OTEL_ERROR_DESCRIPTION.into(),
span_data.status_message.into_owned(),
);
}
tags.insert(OTEL_STATUS_CODE.into(), status_code.into());
}
Expand All @@ -80,7 +83,7 @@ pub(crate) fn into_zipkin_span(local_endpoint: Endpoint, span_data: trace::SpanD
.trace_id(span_data.span_context.trace_id().to_hex())
.parent_id(span_data.parent_span_id.to_hex())
.id(span_data.span_context.span_id().to_hex())
.name(span_data.name)
.name(span_data.name.into_owned())
.kind(if user_defined_span_kind {
None
} else {
Expand Down
7 changes: 3 additions & 4 deletions opentelemetry-zipkin/src/exporter/model/span.rs
Expand Up @@ -64,7 +64,6 @@ mod tests {
use opentelemetry::trace::{SpanContext, SpanId, SpanKind, StatusCode, TraceId};
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::Arc;
use std::time::SystemTime;

#[test]
Expand Down Expand Up @@ -170,15 +169,15 @@ mod tests {
),
parent_span_id: SpanId::from_u64(1),
span_kind: SpanKind::Client,
name: "".to_string(),
name: "".into(),
start_time: SystemTime::now(),
end_time: SystemTime::now(),
attributes: EvictedHashMap::new(20, 20),
message_events: EvictedQueue::new(20),
links: EvictedQueue::new(20),
status_code,
status_message: status_msg,
resource: Arc::new(Default::default()),
status_message: status_msg.into(),
resource: None,
instrumentation_lib: Default::default(),
};
let local_endpoint = Endpoint::new("test".into(), None);
Expand Down
19 changes: 13 additions & 6 deletions opentelemetry/src/global/trace.rs
@@ -1,5 +1,6 @@
use crate::trace::NoopTracerProvider;
use crate::{trace, trace::TracerProvider, Context, KeyValue};
use std::borrow::Cow;
use std::fmt;
use std::mem;
use std::sync::{Arc, RwLock};
Expand Down Expand Up @@ -92,15 +93,21 @@ impl trace::Tracer for BoxedTracer {
/// trace. A span is said to be a _root span_ if it does not have a parent. Each
/// trace includes a single root span, which is the shared ancestor of all other
/// spans in the trace.
fn start_with_context(&self, name: &str, cx: Context) -> Self::Span {
BoxedSpan(self.0.start_with_context_boxed(name, cx))
fn start_with_context<T>(&self, name: T, cx: Context) -> Self::Span
where
T: Into<Cow<'static, str>>,
{
BoxedSpan(self.0.start_with_context_boxed(name.into(), cx))
}

/// Creates a span builder
///
/// An ergonomic way for attributes to be configured before the `Span` is started.
fn span_builder(&self, name: &str) -> trace::SpanBuilder {
trace::SpanBuilder::from_name(name.to_string())
fn span_builder<T>(&self, name: T) -> trace::SpanBuilder
where
T: Into<Cow<'static, str>>,
{
trace::SpanBuilder::from_name(name)
}

/// Create a span from a `SpanBuilder`
Expand All @@ -119,7 +126,7 @@ pub trait GenericTracer: fmt::Debug + 'static {

/// Returns a trait object so the underlying implementation can be swapped
/// out at runtime.
fn start_with_context_boxed(&self, name: &str, cx: Context) -> Box<DynSpan>;
fn start_with_context_boxed(&self, name: Cow<'static, str>, cx: Context) -> Box<DynSpan>;

/// Returns a trait object so the underlying implementation can be swapped
/// out at runtime.
Expand All @@ -138,7 +145,7 @@ where

/// Returns a trait object so the underlying implementation can be swapped
/// out at runtime.
fn start_with_context_boxed(&self, name: &str, cx: Context) -> Box<DynSpan> {
fn start_with_context_boxed(&self, name: Cow<'static, str>, cx: Context) -> Box<DynSpan> {
Box::new(self.start_with_context(name, cx))
}

Expand Down
10 changes: 5 additions & 5 deletions opentelemetry/src/sdk/env.rs
Expand Up @@ -62,7 +62,7 @@ mod tests {
use crate::sdk::env::OTEL_RESOURCE_ATTRIBUTES;
use crate::sdk::resource::{Resource, ResourceDetector};
use crate::sdk::EnvResourceDetector;
use crate::{Key, KeyValue};
use crate::KeyValue;
use std::{env, time};

#[test]
Expand All @@ -75,10 +75,10 @@ mod tests {
assert_eq!(
resource,
Resource::new(vec![
KeyValue::new(Key::new("key".to_string()), "value"),
KeyValue::new(Key::new("k".to_string()), "v"),
KeyValue::new(Key::new("a".to_string()), "x"),
KeyValue::new(Key::new("a".to_string()), "z"),
KeyValue::new("key", "value"),
KeyValue::new("k", "v"),
KeyValue::new("a", "x"),
KeyValue::new("a", "z"),
])
);

Expand Down
27 changes: 13 additions & 14 deletions opentelemetry/src/sdk/export/trace/mod.rs
@@ -1,16 +1,15 @@
//! Trace exporters
use std::fmt::Debug;
use std::sync::Arc;
use std::time::SystemTime;

use async_trait::async_trait;
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};

use crate::{
sdk,
trace::{Event, Link, SpanContext, SpanId, SpanKind, StatusCode, TraceError},
};
use async_trait::async_trait;
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::fmt::Debug;
use std::sync::Arc;
use std::time::SystemTime;

pub mod stdout;

Expand Down Expand Up @@ -66,7 +65,7 @@ pub struct SpanData {
/// Span kind
pub span_kind: SpanKind,
/// Span name
pub name: String,
pub name: Cow<'static, str>,
/// Span start time
pub start_time: SystemTime,
/// Span end time
Expand All @@ -80,9 +79,9 @@ pub struct SpanData {
/// Span status code
pub status_code: StatusCode,
/// Span status message
pub status_message: String,
pub status_message: Cow<'static, str>,
/// Resource contains attributes representing an entity that produced this span.
pub resource: Arc<sdk::Resource>,
pub resource: Option<Arc<sdk::Resource>>,
/// Instrumentation library that produced this span
#[cfg_attr(feature = "serialize", serde(skip))]
pub instrumentation_lib: sdk::InstrumentationLibrary,
Expand Down Expand Up @@ -111,7 +110,7 @@ mod tests {

let parent_span_id = 1;
let span_kind = SpanKind::Client;
let name = "foo/bar baz 人?!".to_string();
let name = "foo/bar baz 人?!".into();
let start_time = crate::time::now();
let end_time = crate::time::now();

Expand All @@ -121,8 +120,8 @@ mod tests {
let links = sdk::trace::EvictedQueue::new(capacity);

let status_code = StatusCode::Ok;
let status_message = String::new();
let resource = Arc::new(sdk::Resource::default());
let status_message = "".into();
let resource = None;

let span_data = SpanData {
span_context,
Expand Down
8 changes: 4 additions & 4 deletions opentelemetry/src/sdk/resource.rs
Expand Up @@ -260,10 +260,10 @@ mod tests {
assert_eq!(
resource,
Resource::new(vec![
KeyValue::new(Key::new("key".to_string()), "value"),
KeyValue::new(Key::new("k".to_string()), "v"),
KeyValue::new(Key::new("a".to_string()), "x"),
KeyValue::new(Key::new("a".to_string()), "z")
KeyValue::new("key", "value"),
KeyValue::new("k", "v"),
KeyValue::new("a", "x"),
KeyValue::new("a", "z")
])
)
}
Expand Down

0 comments on commit a0b80e8

Please sign in to comment.