Skip to content

Instantly share code, notes, and snippets.

@GromNaN
Created May 17, 2024 06:47
Show Gist options
  • Save GromNaN/bb1711fb3d9607e1c5f3bce2eaacd402 to your computer and use it in GitHub Desktop.
Save GromNaN/bb1711fb3d9607e1c5f3bce2eaacd402 to your computer and use it in GitHub Desktop.
<?php
use MongoDB\BSON\Document;
use PhpBench\Attributes\Groups;
use PhpBench\Attributes\Iterations;
use PhpBench\Attributes\Revs;
#[Iterations(30)]
class CreateObjectBench
{
private ArrayObject $arrayObject;
private stdClass $stdClass;
private array $array;
private $document;
public function __construct()
{
$data = [];
foreach (range(0, 100) as $i) {
$data['foo'.$i] = 'foo';
}
$this->array = $data;
$this->stdClass = (object) $data;
$this->arrayObject = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
$this->document = Document::fromPHP($data);
}
#[Revs(100_000)]
#[Groups(['array_access'])]
public function benchArray()
{
$value = $this->array['foo50'];
$value = $this->array['foo60'];
$value = $this->array['foo1'];
$value = $this->array['foo50'];
$value = $this->array['foo60'];
$value = $this->array['foo1'];
}
#[Revs(100_000)]
#[Groups(['array_access'])]
public function benchStdClass()
{
$value = $this->stdClass->foo50;
$value = $this->stdClass->foo60;
$value = $this->stdClass->foo1;
$value = $this->stdClass->foo50;
$value = $this->stdClass->foo60;
$value = $this->stdClass->foo1;
}
#[Revs(100_000)]
#[Groups(['array_access'])]
public function benchArrayAccess()
{
$value = $this->arrayObject['foo50'];
$value = $this->arrayObject['foo60'];
$value = $this->arrayObject['foo1'];
$value = $this->arrayObject['foo50'];
$value = $this->arrayObject['foo60'];
$value = $this->arrayObject['foo1'];
}
#[Revs(100_000)]
#[Groups(['array_access'])]
public function benchArrayObject()
{
$value = $this->arrayObject->foo50;
$value = $this->arrayObject->foo60;
$value = $this->arrayObject->foo1;
$value = $this->arrayObject->foo50;
$value = $this->arrayObject->foo60;
$value = $this->arrayObject->foo1;
}
#[Revs(100_000)]
#[Groups(['array_access'])]
public function benchDocument()
{
$value = $this->document['foo50'];
$value = $this->document['foo60'];
$value = $this->document['foo1'];
$value = $this->document['foo50'];
$value = $this->document['foo60'];
$value = $this->document['foo1'];
}
}
PHPBench (1.2.15) running benchmarks...
with PHP version 8.3.6, xdebug ✔, opcache ❌
\CreateObjectBench
benchArray..............................I29 - Mo0.291μs (±0.84%)
benchStdClass...........................I29 - Mo0.281μs (±1.32%)
benchArrayAccess........................I29 - Mo0.357μs (±1.49%)
benchArrayObject........................I29 - Mo0.363μs (±1.19%)
benchDocument...........................I29 - Mo5.986μs (±0.70%)
Subjects: 5, Assertions: 0, Failures: 0, Errors: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment