php / php/php-src

array_key_exists on $GLOBALS takes linear time in PHP 8.1.0+

未关闭
#9,429 3 条评论 6 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Bug Category: Engine Status: Needs Triage
主要语言
C
星标
40.4k
派生
8.2k
平均合并
2 天 15 小时
30 天内合并 PR
103

描述

Description

Compare the following in PHP 8.0.22 vs 8.1.9 (https://3v4l.org/91CFl)

<?php

for ($i = 0; $i < 100000; $i++) {
    $GLOBALS["a$i"] = rand(0, 1000000);
}

$start = microtime(true);
for ($runs = 1000; $runs > 0; $runs--) {
    array_key_exists('a1111111', $GLOBALS);
}
$end = microtime(true);
printf("[GLOBALS]array_key_exists() took %.5f seconds\n", $end - $start);

It takes 0.00002 seconds in 8.0.22, and 1.9 seconds in 8.1.9.

Further testing makes it clear that the speed of array_key_exists on $GLOBALS increases linearly with the size of $GLOBALS.

This regression doesn't affect array_key_exists on non-$GLOBALS arrays, and doesn't affect the speed of isset($GLOBALS[$foo]).

The commit that introduced the slowdown was https://github.com/php/php-src/commit/3c68f38fdaec7a6f81f986a639bdd29716cf8f22, which restricted usage of $GLOBALS in various ways. I'm not sure if this particular side effect was known or intended.

array_key_exists is used somewhat often on $GLOBALS in MediaWiki, most prominently here.

The behavior can be mostly replaced by calling isset($GLOBALS[$foo]), which remains fast, although that has different semantics when the value is null. I'm not aware of a better way to get the full behavior of array_key_exists($foo, $GLOBALS) in constant-time in 8.1+.

PHP Version

PHP 8.1.9

Operating System

Ubuntu 20.04

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

复现 issue 中的 PHP 8.0.22/8.1.9 基准测试,然后检查 commit 3c68f38fdaec7a6f81f986a639bdd29716cf8f22,该 commit 限制了 $GLOBALS 的使用。完成的标准是:array_key_exists($foo, $GLOBALS) 不再随着 $GLOBALS 的大小线性扩展,同时保留其 null 值语义;将结果与 isset 的行为进行比较。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, php
领域
backend, performance
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。