简体   繁体   English

使用二项元组与字典相比有什么优势?

[英]What is the advantage of using a Two Item Tuple versus a Dictionary?

I have code where I return a list of IWebElements and their corresponding names?我有返回 IWebElements 列表及其相应名称的代码? My understanding is that a tuple with two items is basically the same thing but the Dictionary uses hash mapping to relate the two values.我的理解是,包含两个项目的元组基本上是一回事,但 Dictionary 使用哈希映射来关联这两个值。 What is the advantage of using a Two Item Tuple over a Dictionary or vice versa?与字典相比,使用两项元组有什么优势,反之亦然?

public Dictionary<IWebElement, string> SelectAllOptions(IWebDriver driver, ref DataObject masterData)
    {
        //Get the ID of the dropdown menu
        DatabaseRetrieval.GetObjectRepository(ref masterData);
        var strDropMenuId = masterData.DictObjectRepository["ID"];
        //Find the dropdown menu and pull all options into a list
        try
        {
            var dropMenu = new SelectElement(driver.FindElement(By.Id(strDropMenuId)));
            // TODO want to know how we want this list to return. 
            var options = dropMenu.Options as List<IWebElement>;
            if (options != null)
            {
                var values = options.ToDictionary(option => option, option => option.Text);
                return values;
            }
        }

As a general rule, you do not want to "pay" * for possibilities that your program does not need.作为一般规则,您不想为您的程序不需要的可能性“支付” * For example, if your program is interested in retrieving and processing a sequence of pairs (also known as "two-member tuples") but it does not need to perform lookups from the first member of a tuple to the second, then providing a collection of pairs is more efficient:例如,如果您的程序对检索和处理一系列对(也称为“双成员元组”)感兴趣,但它不需要执行从元组的第一个成员到第二个成员的查找,则提供一个集合对更有效:

IEnumerable<Tuple<IWebElement, string>> SelectAllOptions(...)
  • This approach takes less memory, because you do not allocate space for hash buckets这种方法占用的内存更少,因为您没有为哈希桶分配空间
  • This approach takes less CPU, because there is no hash key computation or collision resolution costs这种方法占用更少的 CPU,因为没有哈希键计算或冲突解决成本
  • This approach does not suggest to a reader that the data is intended for lookups.这种方法并不向读者暗示数据是用于查找的。

Of course if the data structure that you return is intended for lookups, then you should either return a dictionary, or construct one on the client side to transfer some of the CPU load from the server to the client.当然,如果数据结构返回旨在用于查找,那么应该返回一个字典,或构建体上的客户端侧的一个从所述服务器传输的一些CPU负荷的给客户端。

* With memory, CPU cycles, decreased readability, etc. *与内存、CPU 周期、可读性降低等有关。

A Tuple<T1, T2> represents a pair of values. Tuple<T1, T2>表示一对值。 That pair don't necessarily have to mean "These two items are related".那对不一定意味着“这两个项目是相关的”。 When using a KeyValuePair<TKey, TValue> , you would expect that given a key, you would get a value and the two would have some sort of connection between one another.当使用KeyValuePair<TKey, TValue> ,你会期望给定一个键,你会得到一个值,并且两者之间会有某种联系。

Tuples implement IComparable and IStructuralEquatable , which makes it easier to compare Tuples.元组实现了IComparableIStructuralEquatable ,这使得比较元组更容易。 Other than that, I would look at it from a logical perspective, do I need to match a given key to a value?, or do I just need to couple together two values and a class might be a bit of an overhead for that.除此之外,我会从逻辑的角度来看它,我是否需要将给定的键与值匹配?或者我是否只需要将两个值耦合在一起,一个类可能会带来一些开销。

One downside of Tuples as I see it, is that you have to deal with properties labeled Item1 and Item2, which might make it a bit less readable.在我看来,元组的一个缺点是您必须处理标记为 Item1 和 Item2 的属性,这可能会降低它的可读性。

Also, remember that a Tuple is a class (an Immutable one) and KeyValuePair is a struct, so when you passing them as arguments you pass Tuple by reference and KeyValuePair by value (except for explicitly declaring ref or out )另外,请记住 Tuple 是一个class (一个不可变的),而KeyValuePair是一个结构,所以当你将它们作为参数传递时,你通过引用传递 Tuple 和通过值传递 KeyValuePair (显式声明refout除外)

One advantage of tuples over dictionaries is that tuples can be named.元组相对于字典的优势之一是元组可以命名。 Using List<(string text, string url)> links is more meaningful than Dictionary<string, string> links .使用List<(string text, string url)> linksDictionary<string, string> links更有意义。

To add to the other answers, there are sometimes advantages to storing key-value data as a list of tuples instead of in a dictionary.要添加到其他答案中,有时将键值数据存储为元组列表而不是字典有好处。

Depending on your needs, it might not be important that your lookups are fast, but it might be important that the order you insert into the list remains fixed.根据您的需要,快速查找可能并不重要,但您插入列表的顺序保持固定可能很重要。 You can iterate through the keys and the values in a dictionary but the order is not defined.您可以遍历字典中的键和值,但未定义顺序。

Another advantage is that you can put as many pairs with the same first element into the list as you want, where with a dictionary you can only have one value per unique key.另一个优点是您可以根据需要将尽可能多的具有相同第一个元素的对放入列表中,而对于字典,每个唯一键只能有一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM