我有以下內(nèi)容:# a.phpfor($i=1; $i<=5000000; $i++) { $arr = []; for($f = 1; $f <= 5; $f++) { $arr[$f] = 'a'; # <-- I am passing an index manually }}和這個:# b.phpfor($i=1; $i<=5000000; $i++) { $arr = []; for($f = 1; $f <= 5; $f++) { $arr[] = 'a'; # <-- Note that I am not passing an index manually }}為什么b.php代碼比代碼快a.php?...在b.php我沒有手動傳遞索引,所以 PHP 計(jì)算它(這不是更慢嗎?),a.php并將定義的索引傳遞給該數(shù)組,所以我對此感到困惑使用 npm 的 gnomon 包進(jìn)行時間測量~/$ php a.php | gnomon 1.0981s Total 1.0985s~/$ php a.php | gnomon 1.1350s Total 1.1358s~/$ php a.php | gnomon 1.1664s Total 1.1668s~/$ php a.php | gnomon 1.1105s Total 1.1108s~/$ php a.php | gnomon 1.1074s Total 1.1078s~/$ php a.php | gnomon 1.0969s Total 1.0973s~/$ php a.php | gnomon 1.0872s Total 1.0875s~/$ php a.php | gnomon 1.0992s Total 1.0996s和~/$ php b.php | gnomon 0.8960s Total 0.8984s~/$ php b.php | gnomon 0.8859s Total 0.8863s~/$ php b.php | gnomon 0.9031s Total 0.9035s~/$ php b.php | gnomon 0.9078s Total 0.9083s~/$ php b.php | gnomon 0.8880s Total 0.8884s~/$ php b.php | gnomon 0.8945s Total 0.8951s~/$ php b.php | gnomon 0.8891s Total 0.8896s~/$ php test.php | gnomon 0.8843s Total 0.8847s
1 回答

慕桂英3389331
TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個贊
在第一個解決方案中,php 必須弄清楚必須使用什么索引來設(shè)置新值并檢查我們是要更新現(xiàn)有元素還是添加新元素。
在b.php
新元素總是放在數(shù)組的末尾,不需要額外的索引檢查。這基本上就是堆棧的工作方式。
- 1 回答
- 0 關(guān)注
- 135 瀏覽
添加回答
舉報(bào)
0/150
提交
取消