Opened 6 years ago
Last modified 3 years ago
#46388 new enhancement
WP_User::get_data_by(): Cache non-existent users to prevent triggering multiple queries
Reported by: | Asgaros | Owned by: | |
---|---|---|---|
Milestone: | Future Release | Priority: | normal |
Severity: | normal | Version: | 5.2 |
Component: | Cache API | Keywords: | reporter-feedback needs-patch |
Focuses: | performance | Cc: |
Description
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)
Change History (3)
#1
follow-up:
↓ 2
@
3 years ago
- Keywords reporter-feedback added
Can we find ourselves in a situation where the ID is *created* after it's cached as non existent? If yes that operation should invalidate the cache.
#2
in reply to:
↑ 1
@
3 years ago
- Keywords needs-patch added; has-patch removed
- Milestone changed from Awaiting Review to Future Release
Replying to andraganescu:
Right, this ticket is a good idea but will need the "full" cache handling including cache busting or resetting on creating new user, etc.
Add patch file for caching of non-existent users