不同的 ETS table 类型之间有什么区别?

What are the differences between different ETS table types?

根据 manual 有 4 种类型的 ETS 表:

  • set – The table is a set table: one key, one object, no order among objects. This is the default table type.
  • ordered_set – The table is a ordered_set table: one key, one object, ordered in Erlang term order, which is the order implied by the < and > operators. Tables of this type have a somewhat different behavior in some situations than tables of other types. Most notably, the ordered_set tables regard keys as equal when they compare equal, not only when they match. This means that to an ordered_set table, integer() 1 and float() 1.0 are regarded as equal. This also means that the key used to lookup an element not necessarily matches the key in the returned elements, if float()'s and integer()'s are mixed in keys of a table.
  • bag – The table is a bag table, which can have many objects, but only one instance of each object, per key.
  • duplicate_bag – The table is a duplicate_bag table, which can have many objects, including multiple copies of the same object, per key.

虽然从他们的描述中我不太明白他们之间的区别。这里的“对象”和“对象的实例”是什么?

set

这是一个规则映射,其中每个键都是唯一的,并且指的是一个元组。对单个键的每次后续写入都将始终覆盖该键下的现有条目。

1> T = ets:new(t, [set]).
2> ets:insert(T, {1, a}).
3> ets:insert(T, {1, b}).
3> ets:insert(T, {1, b}).
4> ets:insert(T, {1.0, c}).
5> ets:lookup(T, 1).
[{1,b}]

ordered_set

就像 set 一样,但是通过标准比较运算符保持元素的顺序并通过 == 运算符解决相等问题。因此键 11.0 被视为等价的。

1> T = ets:new(t, [set]).
2> ets:insert(T, {1, a}).
3> ets:insert(T, {1, b}).
3> ets:insert(T, {1, b}).
4> ets:insert(T, {1.0, c}).
5> ets:lookup(T, 1).
[{1.0,c}]

bag

它是一个独特的元组集合。只要条目在值的某处不同,条目就可以共享键。

1> T = ets:new(t, [bag]).
2> ets:insert(T, {1, a}).
3> ets:insert(T, {1, b}).
4> ets:insert(T, {1, b}).
4> ets:insert(T, {1.0, c}).
5> ets:lookup(T, 1).
[{1,a},{1,b}]

duplicate_bag

bag 相同,但不是唯一的。元组可以重复意味着每次后续添加相同元素都会在 table

中添加新条目
1> T = ets:new(t, [duplicate_bag]).
2> ets:insert(T, {1, a}).
3> ets:insert(T, {1, b}).
4> ets:insert(T, {1, b}).
4> ets:insert(T, {1.0, c}).
5> ets:lookup(T, 1).
[{1,a},{1,b},{1,b}]