Skip to content

Instantly share code, notes, and snippets.

@Ocramius
Last active August 26, 2020 04:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ocramius/7453564 to your computer and use it in GitHub Desktop.
Save Ocramius/7453564 to your computer and use it in GitHub Desktop.
`in_array` vs `array_unique` performance example (just a test, not really interesting data)
tests
composer.lock
composer.phar
vendor
<?php
namespace ArrayTest;
use Athletic\AthleticEvent;
class ArrayEvent extends AthleticEvent
{
private $arrayWithMatch = [];
private $arrayWithoutMatch = [];
public function setUp()
{
$this->arrayWithMatch = ['foo', 'bar', 'baz', 'tar', 'tab', '*'];
$this->arrayWithoutMatch = ['foo', 'bar', 'baz', 'tar', 'tab'];
}
/**
* @baseline
* @iterations 100000
* @group in_array-performance
*
* @return mixed
*/
public function inArrayPerformanceWithMatch()
{
if(! in_array('*', $this->arrayWithMatch)) {
$this->arrayWithMatch[] = '*';
}
return $this->arrayWithMatch;
}
/**
* @iterations 100000
* @group in_array-performance
*
* @return mixed
*/
public function arrayUniquePerformanceWithMatch()
{
$this->arrayWithMatch[] = '*';
return array_unique($this->arrayWithMatch);
}
/**
* @iterations 100000
* @group in_array-performance
*
* @return mixed
*/
public function inArrayPerformanceWithoutMatch()
{
if(! in_array('*', $this->arrayWithoutMatch)) {
$this->arrayWithoutMatch[] = '*';
}
return $this->arrayWithoutMatch;
}
/**
* @iterations 100000
* @group in_array-performance
*
* @return mixed
*/
public function arrayUniquePerformanceWithoutMatch()
{
$this->arrayWithoutMatch[] = '*';
return array_unique($this->arrayWithoutMatch);
}
}
{
"require": {
"php": ">=5.4",
"athletic/athletic": "~0.1.7"
},
"autoload": {
"classmap": [
"tests/"
]
}
}
ArrayTest\ArrayEvent
in_array-performance
Method Name Iterations Average Time Ops/s Relative
------------------------------ ---------- ------------ -------------- --------- ---------
inArrayPerformanceWithMatch : [Baseline] [100,000 ] [0.0000005988693] [1,669,813.36391]
arrayUniquePerformanceWithMatch: [100,000 ] [0.0000017494082] [571,621.86288] [292.12%]
inArrayPerformanceWithoutMatch: [100,000 ] [0.0000008184958] [1,221,753.44157] [136.67%]
arrayUniquePerformanceWithoutMatch: [100,000 ] [0.0000013450456] [743,469.23618] [224.60%]
#/bin/sh
curl -s https://getcomposer.org/installer | php
php composer.phar install
mkdir tests
cp ArrayEvent.php tests/
time php -n ./vendor/bin/athletic -p ./tests/ -b ./vendor/autoload.php -f GroupedFormatter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment