有效地“修改”一个ImmutableMap [英] Efficiently "modifying" an ImmutableMap

查看:205
本文介绍了有效地“修改”一个ImmutableMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用Guava作为其不可变的集合,但我很惊讶地发现,他们的地图没有方法轻松创建新的地图,稍作修改。最重要的是,他们的构建器不允许为键分配新的值或删除键。

We're currently using Guava for its immutable collections but I was surprised to find that their maps don't have methods to easily create new maps with minor modifications. And on top of that, their builder doesn't allow assigning new values to keys, or removing keys.

所以如果我想修改一个值,这里是我希望能够做到:

So if I wanted to modify just one value, here's what I would like to be able to do:

ImmutableMap<Guid, ImmutableMap<String, Integer>> originalMap = /* get the map */;
ImmutableMap<Guid, ImmutableMap<String, Integer>> modifiedMap =
    originalMap.cloneAndPut(key, value);

以下是Guava期待我做的事情:

Here's what it looks like Guava are expecting me to do:

ImmutableMap<Guid, ImmutableMap<String, Integer>> originalMap = /* get the map */;
Map<Guid, ImmutableMap<String, Integer>> mutableCopy = new LinkedHashMap<>(originalMap);
mutableCopy.put(key, value);
originalMap = ImmutableMap.copyOf(mutableCopy);
/* put the map back */

通过这样做,我得到一个新的地图与我想要的修改。原始副本是未修改过的,我将使用原子引用将该东西放回来,以便整个安装程序都是线程安全的。

By doing this I get a new copy of the map with the modification I want. The original copy is untouched and I will be using an atomic reference to put the thing back so the whole setup is thread-safe.

这是很慢的。

这里的封面有很多浪费的复制。假设地图中有1,024个桶。这是1,023个桶,您不必要地重新创建(每次两次),当您可以使用这些不可变桶时,只能克隆其中一个。

There is a lot of wasted copying going on under the covers here. Suppose there's 1,024 buckets in the map. That's 1,023 buckets which you're unnecessarily creating all over again (twice each, too), when you could have used those immutable buckets as-is and cloned only one of them.

所以我猜想:


  1. 是否有一种埋在某种地方的Guava实用程序? (它不在地图或ImmutableMap.Builder中。)

  1. Is there a Guava utility method buried somewhere for this sort of thing? (It isn't in Maps or on the ImmutableMap.Builder.)

有没有其他Java库可以得到这样的事情?我的印象是,Clojure有这样的东西,但我们还没有准备好切换语言...

Is there any other Java library which gets this sort of thing right? I am under the impression that Clojure has this sort of thing under the hood but we're not ready to switch languages just yet...


推荐答案

有点意外的功能Java的映射是可变的,如番石榴的。列表是不可改变的,我会期望的。

A bit unexpected the map of Functional Java is mutable like Guava's. The list is immutable tough as I would expect.

Googling为持久集合java提出:pcollections。有一个地图实施

Googling for "persistent collection java" brought up: pcollections. There are's a Map implementation.

在实际使用任何其他实现之前,我将基于Guava的内存和性能特征进行基准测试。如果还好,我不会感到惊讶。

Before actually using any other implementation I would benchmark the memory and performance characteristics against Guava. I would not be surprised if it's still better.

这篇关于有效地“修改”一个ImmutableMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆