[英]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密集程度,请选择:
ID
< - > String
,在组件之间共享 String
- > Rc<str>
如果你买得起后者,我肯定会建议。 另请注意,您可以在Rc
: Rc<(MetricType, str)>
折叠MetricType
。
然后你仍然需要左右调用clone
,但每个只是一个廉价的非原子增量操作......并且移动到多线程就像交换Arc
for Rc
一样简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.