Make WordPress Core


Ignore:
Timestamp:
03/06/2026 08:04:31 PM (2 months ago)
Author:
dmsnell
Message:

Functions: Memoize wp_normalize_path().

wp_normalize_path() is called thousands of times on a given request. This patch adds memoization via a function-local static variable. This reduces the call count to the underlying wp_is_stream() function, and measured in testing around a 66% cache hit rate.

In testing, for a site making 4000 calls to wp_normalize_path(), this patch led to a reduction in runtime from 1.4 ms to 0.4 ms on the test computer. While small, this time occurs early in the hotpath of the loading WordPress.

Developed in: https://github.com/WordPress/wordpress-develop/pull/10770
Discussed in: https://core.trac.wordpress.org/ticket/64538

Props dmsnell, josephscott, mreishus, westonruter.
Fixes #64538.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/functions.php

    r61710 r61857  
    21802180 * @since 4.5.0 Allows for Windows network shares.
    21812181 * @since 4.9.7 Allows for PHP file wrappers.
     2182 * @since 7.0.0 Uses a static cache to store normalized paths.
    21822183 *
    21832184 * @param string $path Path to normalize.
    21842185 * @return string Normalized path.
    21852186 */
    2186 function wp_normalize_path( $path ) {
    2187     $wrapper = '';
     2187function wp_normalize_path( $path ): string {
     2188    $path = (string) $path;
     2189
     2190    static $cache = array();
     2191    if ( isset( $cache[ $path ] ) ) {
     2192        return $cache[ $path ];
     2193    }
     2194
     2195    $original_path = $path;
     2196    $wrapper       = '';
    21882197
    21892198    if ( wp_is_stream( $path ) ) {
     
    21972206
    21982207    // Replace multiple slashes down to a singular, allowing for network shares having two slashes.
    2199     $path = preg_replace( '|(?<=.)/+|', '/', $path );
     2208    $path = (string) preg_replace( '|(?<=.)/+|', '/', $path );
    22002209
    22012210    // Windows paths should uppercase the drive letter.
     
    22042213    }
    22052214
    2206     return $wrapper . $path;
     2215    $cache[ $original_path ] = $wrapper . $path;
     2216    return $cache[ $original_path ];
    22072217}
    22082218
Note: See TracChangeset for help on using the changeset viewer.