Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP Memory Management – A Simple Guide

INTRODUCTION
MEMORY TROUBLE?

Welcome to a tutorial and tips on PHP Memory management. Are you running out of memory from hungry PHP scripts? Well, memory is cheap these days, and it sure is tempting to just go the easy way of “buy more memory, allocate more to PHP”.

But when it comes to a busy system, just a couple of simple changes and ninja coding techniques can bring an improvement in performance – Possibly help to use fewer system resources, and eliminates the need to buy more hardware needlessly.

So just how do we measure the Memory Usage in PHP? What are the few ninja techniques that can help improve performance? Read on to find out!

I have included a zip file with all the source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
Memory Usage Tracking

Section B
Limit Memory Usage

Section C
Coding Tips

Extra
Useful Bits

Extra
Source Code Download

Closing
What’s Next?

SECTION A
MEMORY USAGE TRACKING

For this first section of the guide, we will be walking through the ways to track memory usage in PHP; The first step of any attempt to optimize performance is to be able to monitor it.

CHECK MEMORY USAGE

Thankfully, no additional tools are required since PHP comes with native functions that will show the current memory usage. All we need to do is to use memory_get_usage() to show the current memory usage, and we can even pass in a true parameter to get the total system memory allocated to PHP.

1-check-memory.php
";
echo "SCRIPT USAGE - " . memory_get_usage(). "
"; $foo = []; for ($i=0; $i"; unset($foo); echo memory_get_usage() . "
"; ?>

PEAK MEMORY USAGE

But of course, it will be dumb for us to be adding “memory checkpoints” everywhere in the script… So thankfully, there is another memory_get_peak_usage() function that will tell us the peak memory usage.

2-peak-memory.php
";
echo "SCRIPT USAGE NOW - " . memory_get_usage(). "
"; $foo = []; for ($i=0; $i"; ?>

MEMORY USAGE PROFILING

If you want to have even more detailed information of the memory usage at specific points in the script, you are going to need to write your own monitoring script or use a tool – Xdebug is one that is capable of doing memory profiling.

SECTION B
LIMIT MEMORY USAGE

Now that you have mastered the first ninja move of tracking memory usage, we shall move on to the next move of limiting (or raising) the memory limit for PHP scripts.

PHP CONFIG FILE

If you are running into an “out-of-memory” problem, the laziest fix is to just raise the memory limits set in the php.ini config file.

php.ini
memory_limit=256M

But please take note that if you change the php.ini file, it will affect the entire server. This can be potentially deadly when multiple scripts go berserk and cause a server crash. So if you want to change the limits in php.ini, please do so sparingly, and only after you have made sure the server can handle the load.

INLINE SET LIMIT

This is an alternative that I will recommend doing instead – 

3-set-memory.php

This way, the memory limitation will only be raised for this particular script.

TO RAISE OR NOT TO RAISE?

Well, if you have to crunch out a report or do a transaction that requires a massive amount of memory, then so be it… But try to keep these heavy-duty tasks to the less busy hours, and adopt some coding techniques to optimize the performance of such scripts.

SECTION C
CODING TIDBITS

Finally, we will walk through some of the stuff you can do on the coding side to optimize the performance and memory usage in this section.

READ RESULTS FROM THE DATABASE LINE-BY-LINE

4-db-read-line.php
 PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false
  ]
) or die("Failed to connect to the database");

// SQL
$stmt = $pdo->prepare("SELECT * FROM `test`");
$stmt->execute();

// FETCH ALL AT ONCE - THIS IS WHAT SOME PEOPLE DO
// $results = $stmt->fetchAll();
// print_r($results);

// FOR MASSIVE SETS, FETCH LINE-BY-LINE INSTEAD.
while ($row = $stmt->fetch(PDO::FETCH_NAMED)) {
  print_r($row);
}

// CLOSE DATABASE CONNECTION
if ($stmt !== null) { $stmt = null; }
if ($pdo !== null) { $pdo = null; }

// PEAK MEMORY USED
echo "PEAK USAGE - " . memory_get_peak_usage() . "
"; ?>

This is actually a rather common newbie mistake – Trying to pull out a million rows of data, and squeezing them into an array all-at-once… Of course, that will not end well. The smarter way to do it is to deal with the data row-by-row instead.

READ FILES LINE-BY-LINE

5-file-read-line.php
";
?>

Same old story, but trying to read a massive file into a single string; Read line-by-line instead.

COMPACT ALGORITHMS

6-compact.php
 $varB) {
  $varC = $varA;
} else {
  $varC = $varB;
}
*/

// THIS IS BETTER
$varC = $varA > $varB ? $varA : $varB ;

// PEAK MEMORY USED
echo "PEAK USAGE - " . memory_get_peak_usage() . "
"; ?>

Sometimes, we do stupid things and go around in circles… So please do review your scripts from time-to-time, and simplify it if you can. A less confusing streamlined code equals better performance.

CUT THE USELESS VARIABLES!

7-cut-var.php
";
?>

Some of you code ninjas may laugh and brush this aside as “trivial”. How much memory can a single variable take? Well, the more useless variables you have floating around, the more memory the script consumes. Keep a hundred of such useless flags and variables in a huge project, and you will see the performance get hit hard.

MANUALLY REMOVE TEMPORARY FLAGS

8-manual-cut.php

Don’t need the temporary variables anymore? Clean them up.

DIRECT OUTPUT FROM DATABASE

9-direct-output.php
 PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false
  ]
) or die("Failed to connect to the database");

// HTTP HEADERS
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"export.csv\"");

// SQL
$stmt = $pdo->prepare("SELECT * FROM `test`");
$stmt->execute();

// FETCH & DIRECTLY OUTPUT
while ($row = $stmt->fetch(PDO::FETCH_NAMED)) {
  echo implode(",", $row) . "\r\n";
}

// CLOSE DATABASE CONNECTION
if ($stmt !== null) { $stmt = null; }
if ($pdo !== null) { $pdo = null; }
?>

When it comes to generating reports, some code ninjas may think – Fetch data from the database into an array first, then format that array, then output it. Well, there is actually a more effective way – That is to directly format and output as we read from the database.

EXTRA
USEFUL BITS

That’s all for this project, and here is a small section on some links that may be useful to you.

REFERENCES

  • PHP – Get memory usage
  • PHP – Get peak memory usage
  • Garbage collecting cycles in PHP

EXTRA
DOWNLOAD

Finally, here is the download link to all the examples as promised.

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post Php Memory Management – A Simple Guide appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

PHP Memory Management – A Simple Guide

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×