array_key_exists() micro-optimization

Created on 20 July 2016, over 8 years ago
Updated 21 March 2023, over 1 year ago

Problem/Motivation

isset() is fast but doesn't take in account NULL values, we can use it ahead of an array_key_exists() check to glean some of it's speed but PHP's short circuit ||
http://www.zomeoff.com/php-fast-way-to-determine-a-key-elements-existanc...

Proposed resolution

Before
if (array_key_exists($key, $array))

After
if (isset($array[$key]) || array_key_exists($key, $array))

Performance profiling

Scenario: 50 nodes generated on the homepage.

With warm cache but caches turned off with example.settings.local.php used.

After drush cr with the same.

Exceptions

If the array variable can potentially be an object without array access, array_key_exists() will ignore that but isset() will throw an Fatal Error in trying to use it as an array.
Example

// drush scr test.php
use Symfony\Component\HttpFoundation\ParameterBag;
$name = 'test';
$raw_parameters = new ParameterBag([$name => $name]);
if (isset($raw_parameters[$name]) && array_key_exists($name, $raw_parameters)) {
  print 'test';
}
πŸ“Œ Task
Status

Fixed

Version

8.5 ⚰️

Component
BaseΒ  β†’

Last updated about 5 hours ago

Created by

πŸ‡¨πŸ‡¦Canada joelpittet Vancouver

Live updates comments and jobs are added and updated live.
  • Performance

    It affects performance. It is often combined with the Needs profiling tag.

  • Novice

    It would make a good project for someone who is new to the Drupal contribution process. It's preferred over Newbie.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024