无法将keyValuePair直接添加到Dictionary [英] Can't add keyValuePair directly to Dictionary

查看:553
本文介绍了无法将keyValuePair直接添加到Dictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 KeyValuePair< T,U> 添加到字典< T,U> 和I不能。我必须分别传递键和值,这意味着Add方法必须创建一个新的KeyValuePair对象来插入,这不能很有效。我不能相信在Add方法中没有一个 Add(KeyValuePair< T,U>)重载。任何人都可以提出这种明显的疏忽的可能原因吗?

I wanted to add a KeyValuePair<T,U> to a Dictionary<T, U> and I couldn't. I have to pass the key and the value separately, which must mean the Add method has to create a new KeyValuePair object to insert, which can't be very efficient. I can't believe there isn't an Add(KeyValuePair<T, U>) overload on the Add method. Can anyone suggest a possible reason for this apparent oversight?

推荐答案

备份一下...在走下路之前你应该确定创建一个新的KeyValuePair是否真的这么低效。

Backup a minute...before going down the road of the oversight, you should establish whether creating a new KeyValuePair is really so inefficient.

首先,Dictionary类没有内部实现为一组键/值对,而是一堆数组。除此之外,我们假设它只是一组KeyValuePairs,并且看效率。

First off, the Dictionary class is not internally implemented as a set of key/value pairs, but as a bunch of arrays. That aside, let's assume it was just a set of KeyValuePairs and look at efficiency.

首先要注意的是, KeyValuePair 是一个结构。真正的含义是它必须从堆栈复制到堆,以便作为方法参数传递。当KeyValuePair被添加到字典中时,必须第二次复制以确保值类型语义。

The first thing to notice is that KeyValuePair is a structure. The real implication of that is that it has to be copied from the stack to the heap in order to be passed as a method parameter. When the KeyValuePair is added to the dictionary, it would have to be copied a second time to ensure value type semantics.

为了将Key和Value作为参数传递,每个参数可以是值类型或参考类型。如果它们是值类型,则性能将与KeyValuePair路由非常相似。如果它们是引用类型,这实际上可以是更快的实现,因为只需要传递地址,并且只需要很少的复制。在最佳情况和最坏情况下,由于KeyValuePair结构本身的开销增加,此选项比KeyValuePair选项略好。

In order to pass the Key and Value as parameters, each parameter may be either a value type or a reference type. If they are value types, the performance will be very similar to the KeyValuePair route. If they are reference types, this can actually be a faster implementation since only the address needs to be passed around and very little copying has to be done. In both the best case and worst case, this option is marginally better than the KeyValuePair option due to the increased overhead of the KeyValuePair struct itself.

这篇关于无法将keyValuePair直接添加到Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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