Skip to content

Instantly share code, notes, and snippets.

@t3ran13
Created December 12, 2018 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t3ran13/9c0d99924337408863d8368f7ca3b3fc to your computer and use it in GitHub Desktop.
Save t3ran13/9c0d99924337408863d8368f7ca3b3fc to your computer and use it in GitHub Desktop.
PHP: Array collection VS Class Collection
<?php
class User
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class UserCollection implements Iterator
{
private $position = 0;
private $array = [];
public function __construct()
{
$this->position = 0;
}
public function rewind()
{
$this->position = 0;
}
public function current()
{
return $this->array[$this->position];
}
public function key()
{
return $this->position;
}
public function next()
{
++$this->position;
}
public function valid()
{
return isset($this->array[$this->position]);
}
public function addUser(User $user)
{
$this->array[] = $user;
}
}
$totalRecord = 100000;
echo PHP_EOL . '// Class collection';
$startTime = microtime(true);
$memStart = memory_get_usage();
$list = new UserCollection();
for ($i = 1; $i <= $totalRecord; $i++) {
$user = new User($i);
$list->addUser($user);
}
foreach ($list as $user) {
/** @var User $user **/
$user->getName();
}
echo PHP_EOL . 'time:' . round(microtime(true) - $startTime, 3);
echo PHP_EOL . 'memory:' . (memory_get_usage() - $memStart);
unset($list);
echo PHP_EOL . '// Array collection';
$startTime = microtime(true);
$memStart = memory_get_usage();
$list = [];
for ($i = 1; $i <= $totalRecord; $i++) {
$user = new User($i);
$list[] = $user;
}
foreach ($list as $user) {
/** @var User $user **/
$user->getName();
}
echo PHP_EOL . 'time:' . round(microtime(true) - $startTime, 3);
echo PHP_EOL . 'memory:' . (memory_get_usage() - $memStart);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment