| 1 | <?php |
|---|
| 2 | /** |
|---|
| 3 | * This file demonstrates a performance issue present in wp_unique_post_slug(). |
|---|
| 4 | * |
|---|
| 5 | * Copy this script to your Wordpress root and run from your browser using "http://localhost/generate-many-posts.php" link. |
|---|
| 6 | * |
|---|
| 7 | * Run several times to see how it's getting slower and slower. Also you can increase POSTS_TO_CREATE constant (but adjust your max_execution time for this). |
|---|
| 8 | * |
|---|
| 9 | * The issue shows itself when you've got a lot post with automatically generated slug (slug, slug-1, slug-2, ..., slug-N). |
|---|
| 10 | * To generate a slug for a new post, Wordpress issues a huge amount of SELECTs for choosing a free name for the slug. |
|---|
| 11 | * The more you have posts with similar names, the bigger amount of SELECTs is: Big-O(N) |
|---|
| 12 | * |
|---|
| 13 | * @author Artem Bisyarin (http://zool.in.ua) |
|---|
| 14 | */ |
|---|
| 15 | define('POSTS_TO_CREATE', 100); |
|---|
| 16 | define('POST_TYPE', 'attachment'); |
|---|
| 17 | //define('POST_TYPE', 'page'); |
|---|
| 18 | //define('POST_TYPE', 'post'); |
|---|
| 19 | |
|---|
| 20 | require_once(dirname(__FILE__) . '/wp-load.php'); |
|---|
| 21 | define('SAVEQUERIES', true); |
|---|
| 22 | |
|---|
| 23 | $postarr_proto = array( |
|---|
| 24 | 'ID' => 0, |
|---|
| 25 | 'post_type' => POST_TYPE, |
|---|
| 26 | 'post_status' => 'publish', |
|---|
| 27 | 'post_title' => 'Generated Post', // post-name will be "generated-page, generated-page-2, ..., generated-page-N" |
|---|
| 28 | 'post_content' => 'Generated post content of the post #' |
|---|
| 29 | ); |
|---|
| 30 | |
|---|
| 31 | |
|---|
| 32 | for ($i = 1; $i <= POSTS_TO_CREATE; $i++) { |
|---|
| 33 | $postarr = $postarr_proto; |
|---|
| 34 | $postarr['post_content'] .= $i; // Make the content somehow unique |
|---|
| 35 | $time_start = microtime(true); |
|---|
| 36 | $old_number_of_queries = count($wpdb->queries); |
|---|
| 37 | $id = wp_insert_post($postarr); |
|---|
| 38 | $time_spent = microtime(true) - $time_start; |
|---|
| 39 | $queries_issued = count($wpdb->queries) - $old_number_of_queries; |
|---|
| 40 | echo "<div>Post #{$i} with id={$id} has been created, for which <b>{$queries_issued}</b> queries issued, and it took {$time_spent} ms</div>"; |
|---|
| 41 | echo str_pad('', 4096) . "\n"; // This must make flush() work |
|---|
| 42 | flush(); |
|---|
| 43 | } |
|---|
| 44 | |
|---|
| 45 | echo "END"; |
|---|