Skip to content

Instantly share code, notes, and snippets.

@hellofromtonya
Created February 11, 2018 19:30
Show Gist options
  • Save hellofromtonya/5e4ededdb6b9b6be69260998f52dcc12 to your computer and use it in GitHub Desktop.
Save hellofromtonya/5e4ededdb6b9b6be69260998f52dcc12 to your computer and use it in GitHub Desktop.
Profile memory usage and execution time when storing in the Beans Action API Container using json_encode
<?php
/**
* Test if we need to encode each action before storing it into the container.
*
* This test will run 1,000,000 cycles using json_encode and take a snapshot of the memory usage and total execution time.
* Then it'll run another million cycles by storing the array into the container, without encoding it.
*
* We'll print out the results.
*/
/**
* Run the test using json_encode().
*
* @since 1.0.0
*
* @return int
*/
function run_with_json_encode() {
$container = array( 'added' => array() );
$action = array(
'hook' => 'foo',
'callback' => 'some_callback',
'priority' => 10,
'args' => 2,
);
$memory_usage = memory_get_usage();
$time = microtime( true );
// Run the test 1million times, adding the action into our container.
for ( $index = 0; $index < 1000000; $index ++ ) {
$container['added'][] = json_encode( $action );
}
// Take a snapshot of the memory we used during the test.
return array(
microtime( true ) - $time,
memory_get_usage() - $memory_usage,
);
}
/**
* Description.
*
* @since 1.0.0
*
* @return int
*/
function run_without_encoding() {
$container = array( 'added' => array() );
$action = array(
'hook' => 'foo',
'callback' => 'some_callback',
'priority' => 10,
'args' => 2,
);
$memory_usage = memory_get_usage();
$time = microtime( true );
// Run the test 1million times, adding the action into our container.
for ( $index = 0; $index < 1000000; $index ++ ) {
$container['added'][] = $action;
}
// Take a snapshot and return.
return array(
microtime( true ) - $time,
memory_get_usage() - $memory_usage,
);
}
$encoded_results = run_with_json_encode();
$array_results = run_without_encoding();
// Print out the results.
echo "\nFor 1,000,000 cycles, the results are:\n\n";
printf( "\tUsing json_encode: %d bytes in %0.6f seconds.\n", number_format( $encoded_results[1] ), $encoded_results[0] );
printf( "\tWithout json_encode: %d bytes in %0.6f seconds.\n", number_format( $array_results[1] ), $array_results[0] );
@hellofromtonya
Copy link
Author

hellofromtonya commented Feb 11, 2018

The results from the above tests:

For 1,000,000 cycles, the results are:

	Using json_encode:     232 bytes in 0.884874 seconds.
	Without json_encode:    96 bytes in 0.139804 seconds.

Using json_encode is both slower and uses more memory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment