Objects versus Arrays

2019-07-21 08:52发布

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 :)

3条回答
对你真心纯属浪费
2楼-- · 2019-07-21 09:28

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-07-21 09:51

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.

查看更多
成全新的幸福
4楼-- · 2019-07-21 09:52

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.

查看更多
登录 后发表回答