Created
February 11, 2018 19:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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] ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The results from the above tests:
Using
json_encode
is both slower and uses more memory.