对于加速克隆哈希映射的 Java 代码有什么建议吗?
我有一个 java 类,其中包含哈希映射作为成员。这个类是由许多对象创建的。在许多这样的情况下,这种类型的一个对象被克隆到另一个对象,然后进行更改。之所以需要克隆,是因为更改会修改哈希图,并且我需要保持原始对象的原始哈希图完好无损。
我想知道是否有人对如何加快克隆部分有任何建议,或者可能有一些避免它的技巧。当我分析代码时,大部分时间都花在克隆这些哈希映射上(它们通常具有非常小的值集,大约几百个)。
(我目前正在使用 colt OpenIntDoubleHashMap 实现。)
I have a java class that contains a hash map as a member. This class is created with many objects. In many of these cases, one object of this type is cloned to another object, and then changed. The cloning is required because the changes modify the hash map, and I need to keep the original hash map of the original object intact.
I am wondering if anyone has any suggestions how to speed up the cloning part, or maybe some trick to avoid it. When I profile the code, most time is spent on the cloning these hash maps (which usually have very small set of values, a few hundreds or so).
(I am currently using the colt OpenIntDoubleHashMap implementation.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用更有效的算法。查看 http://code.google.com/p/pcollections/ 库
PMap
结构允许不可变的映射。更新
如果你的地图很小(你说只有几百个),也许更有效的是两个数组:
在这种情况下,要克隆地图,你只需要使用
System.arraycopy
应该工作得非常快。You should use more effective algorithms for it. Look at the http://code.google.com/p/pcollections/ library, the
PMap
structure which allows immutable maps.UPDATE
If your map is quite small (you said only a few hundreds), maybe more effective would be just two arrays:
In this case to clone the map you just need do use
System.arraycopy
which should work very fast.如果原始地图仅发生变化,则可以为您的地图实现 copy-on-write 包装器偶尔。
Maybe implement a copy-on-write wrapper for your map if the original only changes occasionally.
如果只有一小部分对象发生变化,您可以实现两层结构:
原始地图中需要更改的任何对象都会被克隆、修改并放入第 2 层地图中。
查找首先参考第 2 层地图,如果未找到对象,则返回到第 1 层地图。
If only a small fraction of the objects change, could you implement a two-layer structure:
Any object from the original map that needs to change gets cloned, modified an put into the layer-2 map.
Lookups first consult the layer-2 map and, if the object is not found, fall back to the layer-1 map.