I'm using data pulled from an SQL query to build two charts later in my code. And example query would be something like:
SELECT purchase_location, purchase_item, SUM(purchase_amount) as totalPurchase
FROM purchases
GROUP BY purchase_item_id, purchase_location
Not an exact example, but the idea is there. I then iterate through my results to build the two data sets.
$locationData = [];
$itemData = [];
foreach($queryResults as $result) {
$locationData[$result['purchase_location']] += $result['totalPurchase'];
$itemData[$result['purchase_item']] += $result['totalPurchase'];
}
Since I want the data from two different points of view, I have to use += to get the correct totals. My question is this: doing the += operator on an unset index of an array is incredibly slow. I've found that if I do the following:
if (isset($locationData['purchase_location'])) {
$locationData['purchase_location'] += $result['totalPurchase'];
} else {
$locationData['purchase_location'] = $result['totalPurchase'];
}
Using an = for the first time the index is seen. This speeds up the code significantly (As an example, my code went from 8-10 second run time down to less than half a second). My question is, is that the correct/cleanest way to handle this?
And before anyone mentions, I know I could write the query to handle all of this in this simple case, this was just a really easy example to show the issue, that of using += on an, as of yet, undefined array index.
This speeds up the code significantly (As an example, my code went from 8-10 second run time down to less than half a second)- I don't believe this. The performance test you made is probably invalid.SHOW CREATE TABLE tablefor every table involved in the question and aEXPLAIN queryoutput