Index: src/wp-includes/post.php
===================================================================
--- src/wp-includes/post.php	(revision 52787)
+++ src/wp-includes/post.php	(working copy)
@@ -3083,6 +3083,25 @@
 }
 
 /**
+ * Return the cache key for wp_count_attachments() based on the passed mime type.
+ *
+ * @since 6.0.0
+ * @access private
+ *
+ * @param string|string[] $mime_type Optional. Array or comma-separated list of
+ *                                   MIME patterns. Default empty.
+ * @return string The cache key.
+ */
+function _count_attachments_cache_key( $mime_type = '' ) {
+	$cache_key = sprintf(
+		'attachments%s',
+		! empty( $mime_type ) ? ':' . str_replace( '/', '_', implode( '-', (array) $mime_type ) ) : ''
+	);
+
+	return $cache_key;
+}
+
+/**
  * Count number of attachments for the mime type(s).
  *
  * If you set the optional mime_type parameter, then an array will still be
@@ -3101,6 +3120,14 @@
 function wp_count_attachments( $mime_type = '' ) {
 	global $wpdb;
 
+	$cache_key = _count_attachments_cache_key( $mime_type );
+
+	$counts = wp_cache_get( $cache_key, 'counts' );
+	if ( false !== $counts ) {
+		/** This filter is documented in wp-includes/post.php */
+		return apply_filters( 'wp_count_attachments', $counts, $mime_type );
+	}
+
 	$and   = wp_post_mime_type_where( $mime_type );
 	$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
 
@@ -3110,6 +3137,9 @@
 	}
 	$counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
 
+	$counts = (object) $counts;
+	wp_cache_set( $cache_key, $counts, 'counts' );
+
 	/**
 	 * Modify returned attachment counts by mime type.
 	 *
@@ -3119,7 +3149,7 @@
 	 *                                   mime type.
 	 * @param string|string[] $mime_type Array or comma-separated list of MIME patterns.
 	 */
-	return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
+	return apply_filters( 'wp_count_attachments', $counts, $mime_type );
 }
 
 /**
