Objects versus Arrays

二次信任 提交于 2019-12-11 01:50:23

问题


I am working on a site at the moment, and there is a concentrated focus on efficiency and speed in loading, processing and such like.

I'm using the mysqli extension to get my database bits and bobs, but I'm wondering what's the best / most efficient way of outputting my dataset?

At the moment I'm using $mysqli->fetch_assoc() and a foreach(). Having read http://www.phpbench.com I know that counting my data first makes a difference. (I'm going to optimise after build)

My question is, which is quicker for getting a resultset into a php data thing. Creating an object? A numerical array? An associative array? My thoughts are an object, but I'm unsure.

Just curious, as I'm not familiar with the PHP internals :)


回答1:


There is actually a small benchmark in PHP documentation under mysql_fetch_object's comments:

SELECT * FROM bench... (mysql_fetch_object)

Query time: 5.40725040436
Fetching time: 16.2730708122 (avg: 1.32130565643E-5)
Total time: 21.6803212166

SELECT * FROM bench... (mysql_fetch_array)

Query time: 5.37693023682
Fetching time: 10.3851644993 (avg: 7.48886537552E-6)
Total time: 15.7620947361

SELECT * FROM bench... (mysql_fetch_assoc)

Query time: 5.345921278
Fetching time: 10.6170959473 (avg: 7.64049530029E-6)
Total time: 15.9630172253

Fetching an object is slowest, fetching a numeric array is probably a bit faster than using mysql_fetch_array or mysql_fetch_assoc, but the difference is negligible. In fact, mysql_fetch_array fetches both assoc and numeric, and it's faster than mysql_fetch_assoc, go figure.. But if you're after performance, just don't use mysql_fetch_object.




回答2:


From the manual page of mysql_fetch_object()

Note: Performance

Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant)

As the benchmark given by Tatu suggests, there is a slight difference, but keep in mind the numbers have been cumulated from 100 consecutive queries. I'd say your strategy of not bothering now and optimize later is a good choice.




回答3:


I believe a numerical array is likely to be the most lightweight, followed by associative array, and then an object. I don't think the differences will add up to much, so whichever syntax you're most comfortable with is best.



来源:https://stackoverflow.com/questions/2048189/objects-versus-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!