gpt4 book ai didi

c# - 为什么 KeyValuePair 是 16 个字节?

转载 作者:太空狗 更新时间:2023-10-30 00:39:29 25 4
gpt4 key购买 nike

KeyValuePair<int, int>:    8 bytes
KeyValuePair<long, long>: 16 bytes
KeyValuePair<long, int>: 16 bytes (!!)
KeyValuePair<int, long>: 16 bytes (!!)

我希望后两对只需要 8 (long) + 4 (int) = 12 个字节。为什么占16个?

大小是使用通过 ILGenerator 发出的动态 SizeOf 确定的,如此处所述:Size of generic structure

最佳答案

这是由于data structure Alignment .引用维基百科文章:

Data alignment means putting the data at a memory address equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

由于 int 是 4 个字节,具有 long 的 KeyValuePair 和 int 会导致数据结构未对齐。这将导致性能显着下降。因此,最好在每个记录上“浪费”4 个字节以使数据对齐,从而能够高效地写入和读取。

至于为什么不填充单个整数——不要忘记使用结构/类添加填充变量相对容易——但对于普通值类型,你没有那个结构/类。我猜测所需的额外工作(在 int 周围添加一个虚拟结构以将填充插入其中)不值得性能提升。

这里 32 位和 64 位操作系统之间确实没有区别,它们仍然需要填充和对齐,但填充量可能会有所不同。

在“过去”,您通常必须手动向数据结构添加填充以获得正确的对齐方式,而如今它往往由编译器自动处理。

关于c# - 为什么 KeyValuePair<int, long> 是 16 个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com