4 ms·
I don't have much formal CS training, and I code primarily in PHP. That being said, I don't see how this is useful at all. I've started coding more in PHP5 rece
by zackattack 17y ago
I don't have much formal CS training, and I code primarily in PHP. That being said, I don't see how this is useful at all. I've started coding more in PHP5 recently: my last two projects have been using classes. I started creating a DBHandler class. Then, whenever I need a DB query, I have a method like this:
function getSnsWithoutIds($customerid) {
$query = sprintf("SELECT aim_sn FROM add_queue WHERE aim_id=0 AND cid=%d", $customerid);
$result = mysql_query($query);
$sns = array();
while($row = mysql_fetch_assoc($result)) {
array_push($sns, $row['aim_sn']);
}
return $sns;
}
And then I simply iterate on the array back in the code.
$dbh = new DBHandler();
$arr = $dbh->getSnsWithoutIds();
foreach($arr as $ele) { doSomething(); }
What is the advantage to doing things your way?
- leftnode 17y agoWell, imagine that the query returns 1000 (or a million or what not) results. You've looped through it once already in the getSnsWithoutIds() to build the $sns array (which you should use $sns[] = $row['aim_sn'], its faster). So, you've looped through everything, which takes some time, and now you have a huge data structure in memory that you may not need. Then, you loop through it again with the foreach. What if you wanted to paginate those results quickly? What if you only wanted a subset of the whole pie? This class, as I'll show in a future article, can easily be extended to allow for easy pagination and filtering of your data.
- zackattack 17y agoWell, it takes a trivial amount of time to loop through an array with a million results. So can you please clarify the benefit of the class as-is, besides its purported future extensiblity? I don't get the time to unset() the array before I return it, but you do? BTW I did a test, and it seems that $array[] is a faster way to append.
- jrockway 17y agoBTW I did a test, and it seems that $array[] is a faster way to append. Classic PHP-style micro-optimization. If you can't use the right algorithm, you can at least make the wrong one run 0.34% faster.
- jrockway 17y agoThis intermediate array is a space leak. Database results can be iterated over in constant space; your technique requires linear space.
- zackattack 17y agoCan you explain the dichotomy of constant space / linear space here? Because constant = {whatever} and mine is linear because it necessarily doubles the constant space?