erlang 什么是对Map的键进行排序的有效且符合人体工程学的方法?

fd3cxomn  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(183)

如何将Map中的键按顺序排列?我试过这个方法,但似乎内存效率不高,因为键集有三个副本:

sort_map(In) -> sort_map(In, lists:sort(maps:keys(In))).
sort_map(In, Keys) ->
    lists:foldl(
        fun (Key, Out) -> Out#{Key => maps:get(Key, In)} end,
        #{},
        Keys
    ).

更新

这个问题没有意义:Map中的键不保证按插入顺序保存,如pointed out by @JoseM。我可能误读了Maps EEP中的某些内容。

72qzrwbm

72qzrwbm1#

Maps in Erlang have no 'publicly' defined order since the concept of a "sorted map" has little meaning. Obviously, internally the keys have an order, but you can do little to influence it by changing the order of the insertions (maps are implementing with a Hash Array-Mapped Trie when they have more than 32 elements, you have a really interesting article here ).
Regarding memory efficiency, large Erlang terms are references, so although the key set is copied, it's not a deep copy for the large Keys. (Unless you send them to other process - large binaries are reference-counted)
I'm unsure about what you're trying to achieve here.
You may want to have a look at orddicts (although they are not implemented natively), or implement your own structure.
Recently I had to use a {map(K => _), queue(K)} for a queue where elements could disappear in the middle of the queue. I use the map to track which elements are in the queue and check the presence of an element every pop() . Maybe you can use a similar approach.

8xiog9wr

8xiog9wr2#

在我的计算机上,首先将Map转换为列表,然后对列表进行排序的速度更快:

sort_map(In) ->
    lists:keysort(1, maps:to_list(In)).

使用235886个字符串键的Map,每个键都有一个与该键相同的字符串值,您的解决方案在100次运行中平均花费0.918秒,而上面的解决方案平均花费0.573秒。使用相同大小但具有二进制键和值的Map,平均值分别为0.494秒和0.332秒。

相关问题