From 129843e1497cb21ea241eafd3df9b65c9394f66e Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Tue, 23 May 2023 21:58:56 +0000 Subject: [PATCH] General: Improve performance of the `_wp_array_get()` function. When using a block theme, `_wp_array_get()` is the most called function on the front end of a site. This commit makes a few minor performance optimizations, which add up to a noticeable improvement. Follow-up to [49135], [49143], [49580]. Props aristath, jrf, afercia, costdev, swissspidy, flixos90, spacedmonkey, mukesh27, samiamnot, SergeyBiryukov. Fixes #58376. git-svn-id: https://develop.svn.wordpress.org/trunk@55851 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index 52c447d996..d7ad450680 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -4947,14 +4947,35 @@ function _wp_array_get( $input_array, $path, $default_value = null ) { } foreach ( $path as $path_element ) { - if ( - ! is_array( $input_array ) || - ( ! is_string( $path_element ) && ! is_integer( $path_element ) && ! is_null( $path_element ) ) || - ! array_key_exists( $path_element, $input_array ) - ) { + if ( ! is_array( $input_array ) ) { return $default_value; } - $input_array = $input_array[ $path_element ]; + + if ( is_string( $path_element ) + || is_integer( $path_element ) + || null === $path_element + ) { + /* + * Check if the path element exists in the input array. + * We check with `isset()` first, as it is a lot faster + * than `array_key_exists()`. + */ + if ( isset( $input_array[ $path_element ] ) ) { + $input_array = $input_array[ $path_element ]; + continue; + } + + /* + * If `isset()` returns false, we check with `array_key_exists()`, + * which also checks for `null` values. + */ + if ( array_key_exists( $path_element, $input_array ) ) { + $input_array = $input_array[ $path_element ]; + continue; + } + } + + return $default_value; } return $input_array;