performance - 如何使用对键的引用更新 HashMap 中的条目?

标签 performance rust

我正在编写一个函数,它可以将值插入或更新到作为结构一部分的 HashMap 中。 我的 map 类型为 HashMap<String, Value>其中 Value是我程序中别处定义的枚举。我有一个函数 pub fn bind(&mut self, name: &str, value: Value)在我的结构上,在 HashMap 中插入或更新条目,目前我的代码如下所示:

pub fn bind(&mut self, name: &str, value: Value) -> /* snip */ {
        /* snip */

        self.bindings.insert(name.to_string(), value);

        /* snip */    
}

这很好,如果 name不在 hashmap 中,但如果在 hashmap 中,是否可以通过更新现有条目来避免 to_string 的开销,而不是调用 to_string 并为我们已有的字符串分配更多内存?我想做这样的事情:

pub fn bind(&mut self, name: &str, value: Value) -> /* snip */ {
        /* snip */

        if (self.bindings.contains(name)) {
                // this update method does not exist
                self.bindings.update(name, value);
        } else {
                self.bindings.insert(name.to_string(), value);
        }        
        
        /* snip */    
}

最佳答案

您可以使用 HashMap::get_mut获取对值(如果存在)的引用,这允许您修改它 - 特别是通过分配新值。

Playground

关于performance - 如何使用对键的引用更新 HashMap 中的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68293899/

相关文章:

java - 如何在 Android 中跟踪有关 fragment 的信息

c# - 数组访问是否比模除法更快?

rust - 如何使用 BorrowMut 超特征访问特征默认方法中的结构字段?

rust - 如何从 `FnMut` 返回捕获的变量

rust - "use of moved value"尝试使用同一资源两次

python - 在 Windows 中运行 python 多处理时内存使用率较高

performance - 布隆过滤器中正匹配的后果

performance - 创建按 id 聚合列的变量的更快方法

rust - 如何在具有可变字段的结构上实现 move 语义?

visual-studio-code - 如何获得Visual Studio Code来重置Rust的IntelliSense引擎?