Reputation: 13890
So, let's say I've got a queryable database with 100 data objects in it. I want to show 3 random ones.
I don't have any working code since this is an idea I just had.
Method 1:
mt_rand()
so essentially Query for IDs (1, 15, 67)
then print each one.
OR
Method 2:
mt_rand()
in the loop with a counter ($counter = 0; $counter = ++$counter)
essentially Query ALL posts
if (ID = 1, 15, 67)
then print each one and if ($counter = 3){ break; }
Method 2 sounds like it would give me a nasty large object. While Method 1 sounds like it would be a more expensive DB query. I think Method 1 would be better, but I'm not sure
Upvotes: 0
Views: 80
Reputation: 10918
If your ID column is indexed, which it probably should be, then doing a select with
WHERE id IN (1, 15, 67)
is very cheap. And it will scale even if you have many more rows in your table. Solution 2 will not scale as it selects the whole table and loads it into memory.
Upvotes: 3
Reputation: 3105
I'm sure method 1 is better:
in method 1 the db engine will iterate through all your posts to find the ones you need, then will send only the 3 ones it selected. in method 2, the db engine will also iterate through all your posts, and then will send a larger object (with all your posts), which will for sure take more time.
hope this was helpfull ;)
Upvotes: 3
Reputation: 78006
Method 1 obviously. It wouldn't be a more expensive DB query if you have indexes set up appropriately.
If you are truly curious, you can find your own answer:
<?
$start = microtime();
doMethodOne();
$end = microtime();
echo 'Method 1 took ' . $end - $start . ' ms<br />';
$start = microtime();
doMethodTwo();
$end = microtime();
echo 'Method 2 took ' . $end - $start . ' ms';
Upvotes: 1