Make WordPress Core

Opened 18 years ago

Closed 18 years ago

#3273 closed enhancement (fixed)

Post Meta caching mechanism leads to unnecessary queries

Reported by: markjaquith's profile markjaquith Owned by: markjaquith's profile markjaquith
Milestone: 2.1 Priority: normal
Severity: normal Version: 2.1
Component: Optimization Keywords: post_meta has-patch
Focuses: Cc:


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:

  1. Query a postmeta key for a post not in the cache
  2. 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)

postmeta.diff (3.8 KB) - added by markjaquith 18 years ago.
Patch for trunk
postmeta2.diff (4.0 KB) - added by markjaquith 18 years ago.
slightly updated patch
postmeta4.diff (4.1 KB) - added by markjaquith 18 years ago.
This should be good to go

Download all attachments as: .zip

Change History (5)

18 years ago

Patch for trunk

#1 @markjaquith
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.

18 years ago

slightly updated patch

18 years ago

This should be good to go

#2 @markjaquith
18 years ago

  • Resolution set to fixed
  • Status changed from assigned to closed

(In [4419]) Fix post meta caching system to reduce queries and eliminate redundant WP code. fixes #3273

Note: See TracTickets for help on using tickets.