Make WordPress Core

Opened 19 months ago

#46388 new enhancement

WP_User::get_data_by(): Cache non-existent users to prevent triggering multiple queries

Reported by: Asgaros Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 5.2
Component: Cache API Keywords: has-patch
Focuses: performance Cc:


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' );

Attachments (1)

46388.diff (851 bytes) - added by Asgaros 19 months ago.
Add patch file for caching of non-existent users

Download all attachments as: .zip

Change History (1)

19 months ago

Add patch file for caching of non-existent users

Note: See TracTickets for help on using tickets.