php / php/php-src

array_key_exists on $GLOBALS takes linear time in PHP 8.1.0+

Aperta
#9,429 3 commenti 6 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Bug Category: Engine Status: Needs Triage
Lingua principale
C
Stelle
40.4k
Fork
8.1k
Merge medio
2g 13h
PR unite (30g)
96

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Riproduci il benchmark di PHP 8.0.22/8.1.9 indicato nell’issue, quindi esamina il commit 3c68f38fdaec7a6f81f986a639bdd29716cf8f22, che ha limitato l’uso di $GLOBALS. Il lavoro è completato quando array_key_exists($foo, $GLOBALS) non scala più linearmente con le dimensioni di $GLOBALS, mantenendo al contempo la propria semantica per i valori null; confronta il risultato con il comportamento di isset.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
c, php
Ambito
backend, performance
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.