Been using PHP/MySQL for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using mysql_fetch_object() vs mysql_fetch_assoc() / mysql_fetch_array().
Performance-wise it doesn't matter what you use. The difference is that mysql_fetch_object returns object:
mysql_fetch_assoc() returns associative array:
and mysql_fetch_array() returns array:
|
|||||||||
|
While many OOP fans (and I am an OOP fan) like the idea of turning everything into an object, I feel that the associative array is a better model of a row from a database than an object, as in my mind an object is a set of properties with methods to act upon them, whereas the row is just data and should be treated as such without further complication. |
|||||||||||||
|
Something to keep in mind: arrays can easily be added to a memory cache (eaccelerator, XCache, ..), while objects cannot (they need to get serialized when storing and unserialized on every retrieval!). You may switch to using arrays instead of objects when you want to add memory cache support - but by that time you may have to change a lot of code already, which uses the previously used object type return values. |
|||
|
...is how I've always done it. I prefer to use objects for collections of data instead of arrays, since it organizes the data a little better, and I know I'm a lot less likely to try to add arbitrary properties to an object than I am to try to add an index to an array (for the first few years I used PHP, I thought you couldn't just assign arbitrary properties to an object, so it's ingrained to not do that). |
|||
|
Fetching an array with Not sure if that even matters much, just thought I'd mention it. |
|||||||||||||||
|
Additionally, if you eventually want to apply Memcaching to your MySQL results, you may want to opt for arrays. It seems it's safer to store array types, rather than object type results. |
|||
|
I think the difference between all these functions is insignificant, especially when compared to code readability. If you're concerned about this kind of optimization, use |
|||
|
Speed-wise, Also, with |
||||
|
I vote against Because you get back both numerically indexed columns and column names, this creates an array that is twice as large. It's fine if you don't need to debug your code and view it's contents. But for the rest of us, it becomes harder to debug since you have to wade through twice as much data in an odd looking format. I sometimes run into a project that uses this function then when I debug, I think that something has gone terribly wrong since I have numeric columns mixed in with my data. So in the name of sanity, please don't use this function, it makes code maintenance more difficult |
|||||||
|