Pages

Monday 5 December 2011

PHP: mysql_fetch_assoc Vs. mysql_fetch_array

Recently I've been doing a lot of work to optimise my work so that pages load more quickly and server load is reduced.  When I was looking through to my database calls, typically I've always used the mysql_fetch_assoc function because it always returned less data than the mysql_fetch array which actually returns two arrays - one which has a numeric index and the other which has an associative key index.
Having a play around and doing some benchmarking between 1,000 and 10,000 iterations of a fairly small amount of data, I found that the mysql_fetch_assoc function was between 24% and 31% faster than the mysql_fetch_array function.  Good news for me really as this is how I typically return data from my MySQL database and so I won't be doing any rewriting any time soon.  This is what I expected really as the size of the data processed and returned is half (well less than that really because it's numeric) so good news here.

Of course there are occasions when the mysql_fetch_array function is needed and I'm not questioning its existence at all, but purely as a benchmarking exercise I would pick mysql_fetch_assoc everyday.

As a side note, it's also important that I mention the mysql_fetch_object function as well which is for those of you who prefer the OO notation.  However, using the same benchmark against the mysql_fetch_assoc function, this is still on average between 8% and 14% slower.

I hope this helps anybody who is currently in the process of performance tuning.  Every little bit saved does help to improve the user experience.

1 comment:

Ashok Yadav said...

Really thank you "ChrisStankus" i got stuck in the problem when i was echoing the result returned by mysql_fetch_array(). I was displaying two indexes and i was confused.

Post a Comment