homepage Welcome to WebmasterWorld Guest from 54.227.141.230
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Order by rand() or array_rand()?
What is better and faster?
GreenLeaf




msg:1292100
 1:07 am on Jan 7, 2005 (gmt 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.

 

coopster




msg:1292101
 11:28 am on Jan 7, 2005 (gmt 0)

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.

GreenLeaf




msg:1292102
 9:27 pm on Jan 7, 2005 (gmt 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?

jshpro2




msg:1292103
 5:36 pm on Jan 8, 2005 (gmt 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")
?>

GreenLeaf




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

Thanks a lot, jshpro2!
I didn't knew how to do this.

eaden




msg:1292105
 12:40 am on Jan 9, 2005 (gmt 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.

GreenLeaf




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

Thanks, eaden,
that's an important tip!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved