Opened 18 years ago
Closed 18 years ago
#3273 closed enhancement (fixed)
Post Meta caching mechanism leads to unnecessary queries
Reported by: | markjaquith | Owned by: | markjaquith |
---|---|---|---|
Milestone: | 2.1 | Priority: | normal |
Severity: | normal | Version: | 2.1 |
Component: | Optimization | Keywords: | post_meta has-patch |
Focuses: | Cc: |
Description
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:
isset($post_meta_cache[$post_id][$key])
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.
Attachments (3)
Change History (5)
#1
@
18 years ago
- Component changed from Administration to Optimization
- Keywords has-patch added
- Status changed from new to assigned
- Type changed from defect to enhancement
Mmm, I love posts that have more red than green.
This eliminates some seriously redundant code, and reduces the number of queries made fetching post meta.
I found another issue that is fixed in my patch: subsequent loops would destroy earlier postmeta cache entries. So if the loops had entries in common, the meta for those common entries was being fetched, destroyed, and fetched again. Bad.
Please review and test.
Patch for trunk