wiki.techinc.nl/includes/Settings/Config/GlobalConfigBuilder.php
Tim Starling 6e40c79954 Config builder optimisations (combined)
This is a modified rebase of a patch by Tim,
see I75f405930a7b14561389c59d147640e870146bec.

Some benchmark results (from my laptop):

Loading defaults from config-schema.php:
  - Master:              115/sec ( 8.7ms)
  - I75f4059: (Tim):     575/sec ( 1.7ms)
  - Id9dd0bf: (Daniel): 1120/sec ( 0.9ms)
  - This (Tim+Daniel):  1420/sec ( 0.7ms)

Loading defaults and merging settings (worst case):
  - Master:               80/sec (12.4ms)
  - I75f4059: (Tim):      93/sec (10.8ms)
  - Id9dd0bf: (Daniel):  200/sec ( 4.9ms)
  - This (Tim+Daniel):   682/sec ( 1.5ms)

Original commit message by Tim:

* Explicitly import function array_key_exists to activate the special
  opcode
* Batch creation of MergeStrategy objects
* Batch default assignment to ArrayConfigBuilder

The batches mostly help by allowing more inlining, eliminating some
function calls.

Reduced time for apply/finalize benchmark from 540µs to 170µs.

Co-Authored-By: Tim Starling <tstarling@wikimedia.org>
Change-Id: I3d4dd685eaaa4351801b3bac6ce1592eea925c5f
2022-05-06 11:28:15 +02:00

70 lines
1.8 KiB
PHP

<?php
namespace MediaWiki\Settings\Config;
use Config;
use GlobalVarConfig;
use function array_key_exists;
class GlobalConfigBuilder extends ConfigBuilderBase {
/** @var string */
public const DEFAULT_PREFIX = 'wg';
/** @var string */
private $prefix;
/**
* @param string $prefix
*/
public function __construct( string $prefix = self::DEFAULT_PREFIX ) {
$this->prefix = $prefix;
}
protected function has( string $key ): bool {
$var = $this->getVarName( $key );
return array_key_exists( $var, $GLOBALS );
}
protected function get( string $key ) {
$var = $this->getVarName( $key );
return $GLOBALS[ $var ] ?? null;
}
protected function update( string $key, $value ) {
$var = $this->getVarName( $key );
$GLOBALS[ $var ] = $value;
}
public function setMulti( array $values, array $mergeStrategies = [] ): ConfigBuilder {
// NOTE: It is tempting to do $GLOBALS = array_merge( $GLOBALS, $values ).
// But that no longer works in PHP 8.1!
// See https://wiki.php.net/rfc/restrict_globals_usage
foreach ( $values as $key => $newValue ) {
$var = $this->prefix . $key; // inline getVarName() to avoid function call
// Optimization: Inlined logic from set() for performance
if ( isset( $GLOBALS[$var] ) && array_key_exists( $key, $mergeStrategies ) ) {
$mergeStrategy = $mergeStrategies[$key];
if ( $mergeStrategy && is_array( $newValue ) ) {
$oldValue = $GLOBALS[$var];
if ( $oldValue && is_array( $oldValue ) ) {
$newValue = $mergeStrategy->merge( $oldValue, $newValue );
}
}
}
$GLOBALS[$var] = $newValue;
}
return $this;
}
private function getVarName( string $key ): string {
return $this->prefix . $key;
}
public function build(): Config {
return new GlobalVarConfig( $this->prefix );
}
}