迭代速度和数据类型 [英] Iterating speed and data type

查看:132
本文介绍了迭代速度和数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过数组(或列表,linkedList,Dictionary ect)的迭代速度是否取决于数据类型?

Does the iteration speed through an array (or list,linkedList,Dictionary ect) depend on the data type?

示例:
数组10 bools v / s是一个10个整数的数组?

Example: An array of 10 bools v/s an array of 10 integers?

推荐答案

是的,数据类型很重要。它与迭代无关;它与数据类型有关。

Yes, the datatype matters. It has nothing to do with the iteration; it has everything to do with the datatypes.

值类型

An int 的长度为4个字节。 十进制的长度为16个字节。所以十进制 int 大4倍。每次从数组中检索值时,都会复制该值。如果十进制,则复制16个字节。 (如果是引用类型,则复制引用,通常为4或8个字节)。复制更多字节只会减慢迭代速度。

An int is 4 bytes in length. A decimal is 16 bytes in length. So a decimal is 4 times bigger than an int. Every time you retrieve a value from the array the that value is copied. In case of a decimal al 16 bytes are copied. (In case of a reference type the reference is copied, normally 4 or 8 bytes). Copying more bytes will simply slow down the iteration.

拳击

如果您通过集合进行迭代,也有可能你有改变类型。例如:

If you iterate trough a collection, there is also the possibility that you have change type. For example:

foreach(object o in new int[] { 1,2,3 })
     ....

这会将每个 int 包装到一个对象。这需要时间。这与迭代无关,它与你拳击的事实有关。

This will box every int to an object. This takes time. That has nothing to do with the iteration, it has everything to do with the fact that you are boxing.

施法

最后一个例子:您还必须投射数组:

Last example: There are also arrays in where you have to cast:

foreach(Person p in new object[] { ... })
     ....

铸造也需要额外的时间。

Casting also takes extra time.

编辑

一些时间测量来备份我的声明:

Some time measurements to backup my claim:

这篇关于迭代速度和数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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