PHP MYSQL

SIMPLE PHP MEMORY MANAGEMENT TIPS

CURRENT MEMORY USAGE (BYTES) echo memory_get_usage(); PEAK MEMORY USAGE (BYTES) echo memory_get_peak_usage();

CHECK MEMORY USAGE

01

CONNECT TO DATABASE $pdo = new PDO("mysql:host=HOST; dbname=NAME;charset=utf8", USER, PASSWORD); 

DATABASE FETCH LINE BY LINE (A)

02

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

BAD - FETCH ALL AT ONCE $results = $stmt->fetchAll(); foreach ($results as $r) { print_r($r); }

DATABASE FETCH LINE BY LINE (B)

03

GOOD - FETCH LINE-BY-LINE while ($r = $stmt->fetch())   { print_r($r); }

READ FILE LINE BY LINE

04

BAD - READ ENTIRE FILE $data = file_get_contents("FILE"); print_r($data);

GOOD - READ LINE BY LINE $fh = fopen("FILE", "r"); while (($line = fgets($fh)) !== false)   { echo $line; } fclose($fh);

REDUCE VARIABLES

05

BAD - NEEDLESS VARIABLES $varA = 123; $varB = 234; $varC = $varA + $varB;

GOOD - NO EXTRA VARIABLES $varC = 123 + 234;

MANUAL REMOVE VARIABLES

06

TEMPORARY VARIABLES $varA = 123; $varB = 234; $varC = $varA + $varB;

REMOVE IF NO LONGER IN USE unset($varA); unset($varB); gc_collect_cycles();