Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active February 12, 2024 19:06
Show Gist options
  • Save sabrina-zeidan/68ff4d024d49becda7c8d7d7cd707029 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/68ff4d024d49becda7c8d7d7cd707029 to your computer and use it in GitHub Desktop.
Performance of a few common database queries [WordPress]
//Measure performance of some WP funcitons
$startTime = microtime(true);
$guarded_pages = get_posts([
'posts_per_page' => 100,
'no_found_rows' => true,
'post_type' => SpeedGuard_Admin::$cpt_name,
'post_status' => 'publish',
'fields' => 'ids'
] );
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo "<br>Execution time of get_posts() without meta_query : $elapsed seconds";
$startTime = microtime(true);
$guarded_pages = get_posts([
'posts_per_page' => 100,
'no_found_rows' => true,
'post_type' => SpeedGuard_Admin::$cpt_name,
'post_status' => 'publish',
'fields' => 'ids',
'meta_query' => [
[
'key' => 'sg_test_result',
'value' => 'waiting',
'compare' => 'NOT LIKE',
]
]
] );
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo "<br>Execution time of the same get_posts() with meta_query : $elapsed seconds";
foreach ( $guarded_pages as $guarded_page ) {
$startTime = microtime(true);
get_post_meta( $guarded_page, 'sg_test_result', true );
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo "<br>Execution time of get_post_meta: $elapsed seconds";
break;
}
$startTime = microtime(true);
SpeedGuard_Admin::get_this_plugin_option( 'speedguard_options' );
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo "<br>Execution time of get_option: $elapsed seconds";
$startTime = microtime(true);
get_transient('speedguard-tests-running');
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo "<br>Execution time of get_transient: $elapsed seconds";
//Execution time of get_posts() without meta_query : 0.0004730224609375 seconds
//Execution time of the same get_posts() with meta_query : 0.00031709671020508 seconds
//Execution time of get_post_meta: 0.00012898445129395 seconds
//Execution time of get_option: 1.3828277587891E-5 seconds
//Execution time of get_transient: 0.00056600570678711 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment