Post Meta caching mechanism leads to unnecessary queries
|Reported by:||markjaquith||Owned by:||markjaquith|
If you do get_post_meta($post->ID, 'yourkey', true); on each post in a loop, you'll get:
- One query that fetches all of the postmeta fields (done automatically by WP's update_post_caches())
- One query for each post that does not have 'yourkey'
This can lead to a lot of unnecessary queries.
The problem is that get_post_meta() checks:
This returns false, because the key doesn't exist for that post, and a SQL query is made.
We need to make it check $post_meta_cache[$post_id] . If THAT exists, and the key doesn't, return false.
This would require another behavior change in get_post_meta() to protect against this scenario:
- Query a postmeta key for a post not in the cache
- Query a different postmeta key for that same post (returns false, even though the key may exist)
To remedy this, we could do the following in get_post_meta()
If a request is made for a post's key, and that post isn't in the cache at all, freshen the cache for ALL of that post's meta keys (would require modifying other functions slightly)
I'll work on a patch.
Change History (5)
- Component changed from Administration to Optimization
- Keywords has-patch added
- Status changed from new to assigned
- Type changed from defect to enhancement