From 4f2965e54511c3198b83200480c8765cf58e3595 Mon Sep 17 00:00:00 2001 From: Tonya Mork Date: Mon, 12 Feb 2024 23:08:55 +0000 Subject: [PATCH] Upgrade/Install: Micro-optimizations for getting plugin_file in plugins loader loop. RE: Plugins Dependencies. The following micro-optimization improvements are included for finding each plugin's file relative to the plugins' directory within `wp-settings.php`: * Move `trailingslashit()` before `foreach()`. The path to the plugin directory is a constant. Invoking the `trailingslashit()` within the loop for each plugin is unnecessary and less performant. This commit moves the plugin directory logic to before the loop. The result: the logic will now run 1x instead of Px where P represents the number of active and valid plugins to be loaded. * Use `substr()` instead of `str_replace()` to extract the plugin's file relative to the plugins' directory. `substr()` is more performant than `str_replace()`. Why? Per the PHP handbook: >"This function returns a string or an array with all occurrences of search in subject replaced with the given replace value." `str_replace()` searches the entire string to find and replace each substring occurrence. whereas >"Returns the portion of string specified by the offset and length parameters." `substr()` starts at the given offset and stops at the given (or end of the) string length. In other words, `substr()` iterates over less of and only a specific portion of the given input string, whereas `str_replace()` iterates through the entire string searching for matches (plural). References: * `str_replace()` https://www.php.net/manual/en/function.str-replace.php * `substr()` https://www.php.net/manual/en/function.substr.php * `strlen()` https://www.php.net/manual/en/function.strlen.php * Show the comparison in action https://3v4l.org/TbQ9U. Follow-up to [57545], [57592]. Props hellofromTonya, costdev. Fixes #60510. git-svn-id: https://develop.svn.wordpress.org/trunk@57606 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-settings.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/wp-settings.php b/src/wp-settings.php index 3e01b7df4d..217d97c94d 100644 --- a/src/wp-settings.php +++ b/src/wp-settings.php @@ -499,10 +499,11 @@ if ( ! is_multisite() && wp_is_fatal_error_handler_enabled() ) { } // Load active plugins. -$all_plugin_data = get_option( 'plugin_data', array() ); -$failed_plugins = array(); +$all_plugin_data = get_option( 'plugin_data', array() ); +$failed_plugins = array(); +$plugins_dir_strlen = strlen( trailingslashit( WP_PLUGIN_DIR ) ); foreach ( wp_get_active_and_valid_plugins() as $plugin ) { - $plugin_file = str_replace( trailingslashit( WP_PLUGIN_DIR ), '', $plugin ); + $plugin_file = substr( $plugin, $plugins_dir_strlen ); $plugin_headers = $all_plugin_data[ $plugin_file ]; $errors = array(); $requirements = array(