Skip to content

Instantly share code, notes, and snippets.

@atannus
Last active December 19, 2015 09:49
Show Gist options
  • Save atannus/5936358 to your computer and use it in GitHub Desktop.
Save atannus/5936358 to your computer and use it in GitHub Desktop.
Which means generating a string as per make_word takes more memory than it should.
<?php
/**
*
* When using sprintf and mt_rand to generate a random hex-like string, the
* output seems to take more memory than it should.
*
* Changing the output to a string via a (string) cast or by any other mean,
* such as concatenating a string to it seems to fix the memory usage.
*
* My output
* string ' No trick: 15.51 M' (length=23)
* string ' With trick: 4.45 M' (length=22)
* string ' Delta: 11.06 M' (length=23)
* string ' % delta: 71.31' (length=21)
* string 'trick/no-trick: 0.29' (length=20)
*
* @author Andre Tannus
*
* $ php -v
* PHP 5.4.4-14+deb7u2 (cli) (built: Jun 6 2013 03:36:44)
* Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
* with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans
*/
function make_word()
{
$word = sprintf('%04x', mt_rand(0, 0xffff));
return $word;
}
function main()
{
## Setup
$max = 50000;
## Measurements -----------------------------------------------------------
# No Trick
$j = 0;
$array_no_trick = array();
$mem_no_trick_before = memory_get_usage();
while( $j++ < $max )
{
$array_no_trick[] = make_word();
}
$mem_no_trick_after = memory_get_usage();
# With Trick
$j = 0;
$array_with_trick = array();
$mem_with_trick_before = memory_get_usage();
while( $j++ < $max )
{
$array_with_trick[] = (string) make_word();
}
$mem_with_trick_after = memory_get_usage();
## Maths ------------------------------------------------------------------
$mb = 1024*1024;
$mem_no_trick_delta = round( ($mem_no_trick_after-$mem_no_trick_before)/$mb, 2);
$mem_with_trick_delta = round( ($mem_with_trick_after-$mem_with_trick_before)/$mb, 2);
$delta_memory = $mem_no_trick_delta - $mem_with_trick_delta;
$delta_percent = round( 100 * ($delta_memory / $mem_no_trick_delta),2 );
## Display ----------------------------------------------------------------
var_dump(' No trick: ' . $mem_no_trick_delta . ' M');
var_dump(' With trick: ' . $mem_with_trick_delta . ' M');
var_dump(' Delta: ' . $delta_memory . ' M');
var_dump(' % delta: ' . $delta_percent);
var_dump('trick/no-trick: ' . round($mem_with_trick_delta/$mem_no_trick_delta, 2));
}
main();
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment