Skip to content

Instantly share code, notes, and snippets.

@rgranadino
Last active August 29, 2015 13:55
Show Gist options
  • Save rgranadino/8704673 to your computer and use it in GitHub Desktop.
Save rgranadino/8704673 to your computer and use it in GitHub Desktop.
Magento Memory Leak
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
require 'app/Mage.php';
Mage::app('admin', 'store');
/* @var $customers Mage_Customer_Model_Resource_Customer_Collection */
$customers = Mage::getResourceModel('customer/customer_collection');
$customers->addAttributeToSelect('*');
$customers->setPageSize((isset($argv[1]) && is_numeric($argv[1]))?$argv[1]:2000);
$pages = $customers->getLastPageNumber();
if (in_array('addresshack', $argv)) {
echo "using address alternative...\n";
}
if (in_array('reflection', $argv)) {
echo "using reflection...\n";
$r = new ReflectionProperty(get_class($customers), '_itemsById');
$r->setAccessible(true);
}
for ($currentPage = 1; $currentPage <= $pages; $currentPage++) {
echo "Page: $currentPage ";// leaving in for debugging
_echoMemoryUsage();
$customers->setCurPage($currentPage);
$customers->load();
foreach ($customers as $key => $customer) {
/* @var $customer Mage_Customer_Model_Customer */
if (in_array('addresshack', $argv)) {
$addresses = $customer->getAddressCollection()->setCustomerFilter($customer)->addAttributeToSelect('city');
$address = $addresses->getItemById($customer->getData('default_billing'));
} else {
$address = $customer->getPrimaryBillingAddress();
}
$city = '';
if ($address) {
$city = $address->getCity();
$address->clearInstance();
}
$customer->clearInstance();
$customers->removeItemByKey($key);
}
//make the collection unload the data in memory so it will pick up the next page when load() is called.
$customers->clear();
if (isset($r)) {
$r->setValue($customers, array());
}
}
echo "Final usage: ";
_echoMemoryUsage();
function _echoMemoryUsage()
{
$memUsage = memory_get_usage(true);
if ($memUsage < 1024) {
echo $memUsage." bytes";
} elseif ($memUsage < 1048576) {
echo round($memUsage/1024,2)." kilobytes";
} else {
echo round($memUsage/1048576,2)." megabytes";
}
echo "\n";
}
@jaredkipe
Copy link

Insert between 47 and 48

unset($customers);
$customers = Mage::getResourceModel('customer/customer_collection');
$customers->addAttributeToSelect('*');
$customers->setPageSize((isset($argv[1]) && is_numeric($argv[1]))?$argv[1]:2000);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment