Runtime vs. memory usage

Oftentimes, better runtime can result in higher memory usage. Here is an example to create some strings to test bulk inserts on Redis:

$cmd = "";
$start = microtime(true);
for ($i=0; $i<1000000; $i+=2) $cmd .= "SET entity:".$i.":key value_".($i+1)."\r\n";
echo number_format(microtime(true)-$start, 1)."s\n"; // 0.7s
echo number_format(memory_get_usage(true)/1048576, 1)." MB\n"; // 17.5 MB
echo number_format(memory_get_peak_usage(true)/1048576, 1)." MB\n"; // 17.5 MB

$cmd = "";
$start = microtime(true);
$cmd = vsprintf(str_repeat("SET entity:%d:key value_%d\r\n", 500000), range(0,1000000));
echo number_format(microtime(true)-$start, 1)."s\n"; // 0.4s
echo number_format(memory_get_usage(true)/1048576, 1)." MB\n"; // 30.8 MB
echo number_format(memory_get_peak_usage(true)/1048576, 1)." MB\n"; // 128.5 MB
(PHP 5.4.5, 2.5 GHz, win64)

We see that the same result can be calculated 3 times faster, but memory usage is 75 percent higher. Using arrays in the second version increases peak memory usage by a factor of 7. Note that on a 64bit Linux, peak memory usage is 251.3 MB in the second example.

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP