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.
为情所困2017-05-16 13:10:54
YesArrayList
这样的可使用下标进行随机访问的数据结构,使用下标访问,要比foreach
的方式进行顺序访问,速度要快一些。foreach
这样写法,使用的过程产生一个额外的对象Enumerator
, and each access requires more operations, reducing performance.
foreach
是通过GetEnumerator
获得一个IEnumerator
对象,通过IEnumerator
对象执行MoveNext()
方法和获取Current
Attributes 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...
世界只因有你2017-05-16 13:10:54
foreach
Especially in php7, after modifying the data structure of array, foreach is faster
给我你的怀抱2017-05-16 13:10:54
It is better to use foreach when traversing an array. After all, there is no need to count the array first.