[wp-trac] [WordPress Trac] #46388: WP_User::get_data_by(): Cache non-existent users to prevent triggering multiple queries
WordPress Trac
noreply at wordpress.org
Fri Mar 1 11:24:01 UTC 2019
#46388: WP_User::get_data_by(): Cache non-existent users to prevent triggering
multiple queries
-------------------------+-----------------------------
Reporter: Asgaros | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Cache API | Version: trunk
Severity: normal | Keywords: has-patch
Focuses: performance |
-------------------------+-----------------------------
Assume you use the WP_User::get_data_by() function to get the main user
fields queried against an ID:
{{{
WP_User::get_data_by('ID', 1337);
}}}
If you call this function multiple times - by calling the function
directly or indirectly by using functions like get_userdata or get_avatar
- and an user with the given ID does not exist, the database-query is
getting executed multiple times resulting in duplicate queries:
{{{
SELECT * FROM wp_users WHERE ID = '1337'
}}}
To prevent triggering multiple queries, non-existing users should get
stored inside the WP Object Cache similar as in the get_option() function
for non-existing options.
The attached patch checks if the user ID exists in the WP Object Cache
inside of the notusers-array so the WP_User::get_data_by() function
returns FALSE if this is the case:
{{{
// Prevent non-existent users from triggering multiple queries
$notusers = wp_cache_get( 'notusers', 'users' );
if ( isset( $notusers[ $user_id ] ) ) {
return false;
}
}}}
If the user is not existent in the notusers-array but he also does not
exist inside of the database, the user gets added to the WP Object Cache
before the WP_User:get_data_by() function returns FALSE:
{{{
// User does not exist, so we must cache its non-existence
if ( ! is_array( $notusers ) ) {
$notusers = array();
}
$notusers[ $user_id ] = true;
wp_cache_set( 'notusers', $notusers, 'users' );
}}}
--
Ticket URL: <https://core.trac.wordpress.org/ticket/46388>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list