php - Which is faster, for or foreach?
伊谢尔伦
伊谢尔伦 2017-05-16 13:08:54
0
3
622

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.

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
为情所困

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...

世界只因有你

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template