Welcome to WebmasterWorld Guest from 23.20.179.211

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Order by rand() or array_rand()?

What is better and faster?

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

Junior Member

10+ Year Member

joined:Feb 10, 2003
posts:161
votes: 0


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)

Administrator

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

joined:July 31, 2003
posts:12547
votes: 2


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)

Junior Member

10+ Year Member

joined:Feb 10, 2003
posts:161
votes: 0


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)

New User

10+ Year Member

joined:Dec 25, 2004
posts:32
votes: 0


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)

Junior Member

10+ Year Member

joined:Feb 10, 2003
posts:161
votes: 0


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

Preferred Member

10+ Year Member

joined:Jan 5, 2003
posts:380
votes: 0


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)

Junior Member

10+ Year Member

joined:Feb 10, 2003
posts:161
votes: 0


Thanks, eaden,
that's an important tip!
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members