Welcome to WebmasterWorld Guest from 174.129.96.175

Forum Moderators: coopster & jatar k

Order by rand() or array_rand()?

What is better and faster?

   
1:07 am on Jan 7, 2005 (gmt 0)

10+ Year Member



Hi all!
What method is faster and better in order to get a randomly selected thing: to do "order by rand()" or add sql result to an array and then do array_rand()?
Thanks in advance.
11:28 am on Jan 7, 2005 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



That's completely up to you ;)

I normally let the database do any processing I can in an application so all I have to deal with is the result set. That, and most databases are very fast at handling the task.

9:27 pm on Jan 7, 2005 (gmt 0)

10+ Year Member



Thanks, coopster!
I assume that you've meant that "order by rand()" will be faster, am i right? If so, why so many ready scripts use the array thing?
5:36 pm on Jan 8, 2005 (gmt 0)

10+ Year Member



It all really depends, for something like this I would recommend benchmarking over just taking the easy way out.

<?php
$totaltimes=20;
$timeparts = explode(' ',microtime());
$starttime = $timeparts[1].substr($timeparts[0],1);
for ($x=1;$x<=$totaltimes; $x++) {
// Put code to benchmark here
}
$timeparts = explode(' ',microtime());
$endtime = $timeparts[1].substr($timeparts[0],1);
echo ("Your code ran at about ".(bcsub($endtime,$starttime,6)/$totaltimes)." seconds per loop")
?>

11:47 pm on Jan 8, 2005 (gmt 0)

10+ Year Member



Thanks a lot, jshpro2!
I didn't knew how to do this.
12:40 am on Jan 9, 2005 (gmt 0)

10+ Year Member



One advantage of using array_rand() in php, is if you are running mysql 4.0 and have query caching enabled.

MySQL will NOT cache a query with RAND() or NOW() in it for example, so it has to do the query each time. If it's a "select * from table" without the rand, then it will cache the result until the table is updated.

I think the answer depends on how many rows in the table.

5:36 pm on Jan 11, 2005 (gmt 0)

10+ Year Member



Thanks, eaden,
that's an important tip!
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month