<?php
/**
 * This file demonstrates a performance issue present in wp_unique_post_slug().
 *
 * Copy this script to your Wordpress root and run from your browser using "http://localhost/generate-many-posts.php" link.
 *
 * 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).
 * 
 * The issue shows itself when you've got a lot post with automatically generated slug (slug, slug-1, slug-2, ..., slug-N).
 * To generate a slug for a new post, Wordpress issues a huge amount of SELECTs for choosing a free name for the slug.
 * The more you have posts with similar names, the bigger amount of SELECTs is: Big-O(N)
 *
 * @author Artem Bisyarin (http://zool.in.ua)
 */
define('POSTS_TO_CREATE', 100);
define('POST_TYPE', 'attachment');
//define('POST_TYPE', 'page');
//define('POST_TYPE', 'post');

require_once(dirname(__FILE__) . '/wp-load.php');
define('SAVEQUERIES', true);

$postarr_proto = array(
    'ID' => 0,
    'post_type' => POST_TYPE,
    'post_status' => 'publish',
    'post_title' => 'Generated Post', // post-name will be "generated-page, generated-page-2, ..., generated-page-N"
    'post_content' => 'Generated post content of the post #'
);


for ($i = 1; $i <= POSTS_TO_CREATE; $i++) {
    $postarr = $postarr_proto;
    $postarr['post_content'] .= $i; // Make the content somehow unique
    $time_start = microtime(true);
    $old_number_of_queries = count($wpdb->queries);
    $id = wp_insert_post($postarr);
    $time_spent = microtime(true) - $time_start;
    $queries_issued = count($wpdb->queries) - $old_number_of_queries;  
    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>";
    echo str_pad('', 4096) . "\n"; // This must make flush() work
    flush();
}

echo "END";