使用默认值读取环境变量的最佳方法是什么?
以下两种方法有什么区别,它们如何影响性能?
let consul_host = env::var("CONSUL_HOST")
.as_deref()
.unwrap_or("172.17.0.1")
.to_owned();
或者:
let consul_host = env::var("CONSUL_HOST")
.unwrap_or_else(|| "172.17.0.1".to_owned());
回答
理论上,后一种变体是最有效的,因为它只进行一次字符串分配(在 中var或在 中unwrap_or_else),而前者总是进行一两次。但是,差异充其量只是微小的。如果您真的想一直进行这种微优化(我不推荐),那么您可以完全避免不必要的分配std::borrow::Cow:
fn consul_host() -> Cow<'static, str> {
env::var("CONSUL_HOST")
.map(Into::into)
.unwrap_or("172.17.0.1".into())
}