Which one has better performance, for or foreach? Or do they have their own advantages in processing different data? I hope someone can give me an answer.
YesArrayList这样的可使用下标进行随机访问的数据结构,使用下标访问,要比foreach的方式进行顺序访问,速度要快一些。foreach这样写法,使用的过程产生一个额外的对象Enumerator, and each access requires more operations, reducing performance.
foreach是通过GetEnumerator获得一个IEnumerator对象,通过IEnumerator对象执行MoveNext()方法和获取CurrentAttributes are traversed.
BecauseEnumerator中,做了版本检查处理的工作,所以使用foreach是线程安全
Sofor的效率通常来说是高于foreach, but it cannot be said to be absolute.
So how to choose? My suggestion is to use foreach。而对本地变量,则使用for in some global data structure objects that can be accessed by multiple threads, taking into account both efficiency and safety!
Update: I just checked the information and found that for arrays above 10W, foreach is more efficient, but for arrays of 1W, for is still more efficient. http://blog.csdn.net/w2cschoo...
Yes
ArrayList
这样的可使用下标进行随机访问的数据结构,使用下标访问,要比foreach
的方式进行顺序访问,速度要快一些。foreach
这样写法,使用的过程产生一个额外的对象Enumerator
, and each access requires more operations, reducing performance.foreach
是通过GetEnumerator
获得一个IEnumerator
对象,通过IEnumerator
对象执行MoveNext()
方法和获取Current
Attributes are traversed.Because
Enumerator
中,做了版本检查处理
的工作,所以使用foreach
是线程安全
So
for
的效率通常来说是高于foreach
, but it cannot be said to be absolute.So how to choose? My suggestion is to use
foreach
。而对本地变量,则使用for
in some global data structure objects that can be accessed by multiple threads, taking into account both efficiency and safety!Update: I just checked the information and found that for arrays above 10W, foreach is more efficient, but for arrays of 1W, for is still more efficient.
http://blog.csdn.net/w2cschoo...
foreach
Especially in php7, after modifying the data structure of array, foreach is faster
It is better to use foreach when traversing an array. After all, there is no need to count the array first.