Posts

Showing posts with the label loops

Things you should not do in PHP (update: references)

Here is a list of things you should not do in PHP. Most of the stuff is pretty obvious, but over the years I've seen a lot of them. In most cases, these problems remain hidden until data grows above 10000 entries. So on a development system, things are always fast and there are no problems with memory limits :-) Suppose we have a table with 100k entries: $db->query('create table stats (c1 int(11) primary key, c2 varchar(255))'); $db->query('begin'); for ($i=0; $i<100000; $i++) { $db->query('insert into stats values ('.$i.','.($i*2).')'); } $db->query('commit'); Populate a big array instead of streaming results: $result = $db->query('select * from stats'); $array = $result->fetch_all(); // 35M // or while ($row = $result->fetch_assoc()) $array[] = $row; // 35M // or while ($row = $result->fetch_array()) $array[] = $row; // 44.5M // process $array ... // instead of: while ($row = $result->fetch...

PHP memory consumption with Arrays and Objects (update: generators)

Lessons learned: objects need more memory than arrays (+ 2-10 percent) comparing 32bit to 64bit systems, memory consumption increases by 100-230 percent if array values are numeric, don't save them as strings! saving 1M integers takes 200M of memory with PHP on a 64bit plattform (increase by factor 25) using SplFixedArray can reduce memory usage by 20-130 percent avoid big Arrays and Objects in PHP whenever possible (don't use file('big_file') or explode("\n", file_get_contents('big_file')), etc.) use streams whenever possible (fopen, fsockopen, etc.) use generators when available with PHP 5.5 ( RFC ) If you need to save memory temporarily in your script, you can stringify your array (increasing cpu usage and runtime): $a = array(); for ($i=0; $i $a[] = $i; } $a = implode(',', $a); // or $a = json_encode($a); echo number_format(memory_get_usage(true)/1048576, 2)."\n"; // 8.0 M (64bit), 7.5 M (32bit) Here is a small script to sh...