3. Memory Management in PHP
â Garbage collected
â Reference counts
â Happens after variable is unset, leave function
scope, or script ends, GC buffer is full
â All values are stored in hash tables of ZVAL structs
â Arrays are dynamically allocated by doubling the
size
â Much better in PHP 7 than 5.6
4. What are Iterators and Generators
Iterators are:
â An object that can be iterated over using a loop
â PHP has several built in the SPL
â Can create additional ones
â Special ones are the recursive & filter iterators
Generators are:
â A special kind of custom iterator
â Keywords & interfaces that allow you to define an
Iterator without having to create a class that
implements the interface
6. Generating many values: The object
<?php
namespace ArcIgTalk;
class User
{
public $_id;
public $firstName;
public $lastName;
public $email;
public $password;
public $phoneNumber;
}
7. Generating many values: Generate some values
<?php
...
for ($i = 0; $i < 1000000; $i++) {
$user = new User();
$user->_id = new ObjectID();
$user->email = $faker->email;
$user->password = $faker->password(12, 32);
$user->firstName = $faker->firstName();
$user->lastName = $faker->lastName;
$user->phoneNumber = $faker->phoneNumber;
$users[] = $user;
if ($i % 5000 === 0) {
$collection->insertMany($users);
$users = [];
}
}
14. Processing values: Why does it take so long?
â 3 nested loops
â for ($up = 0; $up < 10000; $up++)
â foreach ($provider->getPagedList($up) as $user)
â foreach ($cursor as $data)
â O(n^3) or n*m*p
15. Processing values: What is going on?
<?php
namespace ArcIgTalk;
class Provider
{
public function getPagedList(int $page = 0, int $limit = 100): array
{
$cursor = $this->collection->find([],['limit' => $limit,'skip' => $page * $limit]);
$users = [];
foreach ($cursor as $data) {
$users[] = $this->createUserEntity($data->getArrayCopy());
}
return $users;
}
}
16. Processing values: What is going on?
<?php
$provider = new Provider(new Client("mongodb://datastore:27017"));
$emailLogPath = __DIR__ . '/../data/user.txt';
$emailLog = fopen($emailLogPath, 'w+');
for ($up = 0; $up < 10000; $up++) {
foreach ($provider->getPagedList($up) as $user) {
fwrite($emailLog, $user->email . "n");
}
}
fclose($emailLog);
17. Processing values: Make it faster
<?php
$provider = new Provider(new Client("mongodb://datastore:27017"));
$emailLogPath = __DIR__ . '/../data/user.txt';
$emailLog = fopen($emailLogPath, 'w+');
for ($up = 0; $up < 1000; $up++) {
foreach ($provider->getPagedList($up, 1000) as $user) {
fwrite($emailLog, $user->email . "n");
}
}
fclose($emailLog);
24. Processing values: Itâs a bit slower
â 3 nested loops
â for ($up = 0; $up < 10000; $up++)
â foreach ($provider->getPagedList($up) as $user)
â foreach ($cursor as $data)
â Effectively only 2
â O(n^2) or n*m
â Extra time for YIELD to go back & forth