如何更好地存储字符串以避免出现许多克隆?
How can I better store a string to avoid many clones?
我正在使用 tokio 的 UdpCodec
特性:
pub trait UdpCodec {
type In;
type Out;
fn decode(&mut self, src: &SocketAddr, buf: &[u8]) -> Result<Self::In>;
fn encode(&mut self, msg: Self::Out, buf: &mut Vec<u8>) -> SocketAddr;
}
我 In
的关联类型是 (SocketAddr, Vec<Metric>)
。 Metric
定义为:
#[derive(Debug, PartialEq)]
pub struct Metric {
pub name: String,
pub value: f64,
pub metric_type: MetricType,
pub sample_rate: Option<f64>,
}
我使用自有字符串来避免关联类型的生命周期限制。但是,我也使用这些指标名称进行 HashMap
查找和插入,这涉及大量克隆,因为我在其他函数中借用了指标。
我如何才能更好地在此 Metric
类型中存储字符串以避免许多低效的克隆?使用 Cow
类型已经在我的脑海中闪过,但它显然也有终生关联。
扩展@Josh 的建议,我建议使用实习。
根据您的任务的内存或 CPU 密集程度,在以下之间做出选择:
- 双重 hash-map:
ID
<-> String
,在组件之间共享
- 单个 hash-map:
String
-> Rc<str>
如果你能负担得起后者,我绝对推荐。另请注意,您可能会在 Rc
中弃牌 MetricType
:Rc<(MetricType, str)>
.
然后你仍然需要左右调用 clone
,但每个都只是一个便宜的 non-atomic 增量操作......并且移动到多线程就像交换一样简单 Arc
Rc
.
我正在使用 tokio 的 UdpCodec
特性:
pub trait UdpCodec {
type In;
type Out;
fn decode(&mut self, src: &SocketAddr, buf: &[u8]) -> Result<Self::In>;
fn encode(&mut self, msg: Self::Out, buf: &mut Vec<u8>) -> SocketAddr;
}
我 In
的关联类型是 (SocketAddr, Vec<Metric>)
。 Metric
定义为:
#[derive(Debug, PartialEq)]
pub struct Metric {
pub name: String,
pub value: f64,
pub metric_type: MetricType,
pub sample_rate: Option<f64>,
}
我使用自有字符串来避免关联类型的生命周期限制。但是,我也使用这些指标名称进行 HashMap
查找和插入,这涉及大量克隆,因为我在其他函数中借用了指标。
我如何才能更好地在此 Metric
类型中存储字符串以避免许多低效的克隆?使用 Cow
类型已经在我的脑海中闪过,但它显然也有终生关联。
扩展@Josh 的建议,我建议使用实习。
根据您的任务的内存或 CPU 密集程度,在以下之间做出选择:
- 双重 hash-map:
ID
<->String
,在组件之间共享 - 单个 hash-map:
String
->Rc<str>
如果你能负担得起后者,我绝对推荐。另请注意,您可能会在 Rc
中弃牌 MetricType
:Rc<(MetricType, str)>
.
然后你仍然需要左右调用 clone
,但每个都只是一个便宜的 non-atomic 增量操作......并且移动到多线程就像交换一样简单 Arc
Rc
.