New SPL Features in PHP 5.3

Matthew Turland
Matthew TurlandSenior Engineer at Synacor, Inc.
New SPL Features in PHP 5.3

       Matthew Turland
            TEK-X
        May 20, 2010
Hi! My name is…

 •   Senior Platform Engineer for Synacor, Inc.
 •   Former author and TE for php|architect
 •   Author of Web Scraping with PHP
 •   Past contributor to Zend Framework
 •   Lead developer of Phergie
 •   ULL alumni with a BS in computer science
And I work for…

 • Provides internet solutions to ISPs, media
   companies, and advertisers
 • International company with offices in Buffalo,
   New York City, Los Angeles, and Amsterdam
 • Clientele includes most of the top 20 cable
   providers in the United States
 • Great company – join us!
What about you?

 •   Used the SPL before?
 •   Using PHP 5.3?
 •   Computer science background?
 •   Knowledge of data structures?
Pre-5.3 SPL Features

 • Classes: ArrayObject, SplFileInfo, SplSubject,
   SplObserver, etc.
 • Iterators: RecursiveIteratorIterator,
   FilterIterator, LimitIterator, etc.
 • Interfaces: ArrayAccess, Countable, Iterator,
   IteratorAggregate, etc.
 • Functions: spl_autoload_register,
   iterator_to_array, spl_object_hash, etc.
Containers

 “A container is a class, a data structure, or
 an abstract data type whose instances are
 collections of other objects. They are used
 to store objects in an organized way
 following specific access rules.”

 Container (data structure) - Wikipedia
Why containers?

 • We already have arrays and strings!
       array()               'string'
Two excellent reasons

 • Versus traditional arrays, there is potential for:
   – Less CPU usage
   – Less memory usage
Arrays are (not always) great

 • Flexible general purpose container
 • Underlying hash table algorithm is not always
   ideal for the task at hand
Warning: Benchmarks Ahead

 • Lies, Outrageous Lies, and Benchmarks
 • PHP 5.3.2 compiled on Ubuntu 9.10
 • Intel Core2Duo 1.83 GHz, 4 GB DDR2 RAM
 • Performance results are shown in executions
   per second rather than time per execution to
   avoid really small numbers
 • Code and results
The List
SplFixedArray - What

 •   Like an array, but with a fixed length
 •   Only allows integers >= 0 for keys
 •   Can be resized, but at a cost
 •   Not compatible with array functions
SplFixedArray - When

 • It’s best to use this when:
   – You know in advance how many elements you
     want to store (e.g. mysql_num_rows)
   – You only need to access elements in sequential
     order
SplFixedArray - Code
    <?php
    $a = array();
    for ($i = 0; $i < $argv[1]; $i++) {
        $a[$i] = $i;
        $i = $a[$i];
    }
    <?php
    $a = new SplFixedArray($argv[1]);
    for ($i = 0; $i < $argv[1]; $i++) {
        $a[$i] = $i;
        $i = $a[$i];
    }
SplFixedArray - EPS
SplFixedArray - Memory
SplDoublyLinkedList - What

 • Mainly intended as a parent class
 • Same unlimited size as arrays without the
   associated hash map algorithm
 • Less performance, but more memory
   efficiency
SplDoublyLinkedList - When

 • It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You only need to access elements in sequential
     order
SplDoublyLinkedList - Code
  <?php
  $a = array();
  for ($i = 0; $i < $argv[1]; $i++) {
      $a[] = $i;
      $i = $a[$i];
  }
  <?php
  $a = new SplDoublyLinkedList($argv[1]);
  for ($i = 0; $i < $argv[1]; $i++) {
      $a[] = $i;
      $i = $a[$i];
  }
SplDoublyLinkedList - EPS
SplDoublyLinkedList - Memory
The Stack
SplStack - What

 • 2 operations
    – Push: [] for both array and SplStack
    – Pop: array_pop() vs SplStack::pop()
 • Last In, First Out (LIFO)
    – The last item pushed onto the top of the stack is
      the first item that will be popped off of the top of
      the stack
SplStack - When

 • It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You only ever need to access the last element you
     stored
SplStack - Code

    <?php
    $a = array();
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        array_pop($a);
    }
SplStack - Code (cont.)

    <?php
    $a = new SplStack;
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        $a->pop();
    }
SplStack - EPS
SplStack - Memory
The Queue
SplQueue - What

 • 2 operations
    – Enqueue: [] for both array and SplQueue
    – Dequeue: array_shift() vs SplQueue::dequeue()
 • First In, First Out (FIFO)
    – The first item added to the end of the queue will
      be the first item removed from the front of the
      queue
SplQueue - When

• It’s best to use this when:
  – You do not know in advance how many elements
    you want to store
  – You only ever need to access the remaining
    element that was stored earliest
SplQueue - Code

    <?php
    $a = array();
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        array_shift($a);
    }
SplQueue - Code (cont.)

    <?php
    $a = new SplQueue;
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        $a->dequeue();
    }
SplQueue - EPS
SplQueue - Memory
The Heap
SplHeap - What
 • 2 operations
   – Insert: [] + sort vs SplHeap::insert()
   – Remove: array_shift() vs SplHeap::extract()
 • Internally reorders items based on comparison
   – SplHeap::compare() can be overridden
 • Subclasses
   – SplMinHeap
   – SplMaxHeap
 • Better worst-case scenario performance
   versus arrays (heap sort versus quick sort)
SplHeap - When

 • It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You need to access elements in an order based on
     how they compare to each other
SplMinHeap - Code

   <?php
   $a = array();
   for($i = 0; $i < $argv[1]; $i++) {
       $a[] = rand(1, $argv[1]);
       sort($a);
   }
   for($i = 0; $i < $argv[1]; $i++) {
       array_shift($a);
   }
SplMinHeap - Code (cont.)

    <?php
    $a = new SplMinHeap;
    for($i = 0; $i < $argv[1]; $i++) {
        $a->insert(rand(1, $argv[1]));
    }
    for($i = 0; $i < $argv[1]; $i++) {
        $a->extract();
    }
SplMinHeap - EPS
SplMinHeap - Memory
The Priority Queue
SplPriorityQueue - What

 • Accepts a priority with the element value
 • Element with highest priority comes out first
 • Priorities may be of any comparable type
 • SplPriorityQueue::compare() can be
   overridden
 • Operates similarly to a heap
     – In fact, it uses a heap internally for storage
SplPriorityQueue - When

 • It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You need to access elements in an order based on
     how priority values associated with those
     elements compare to each other
SplPriorityQueue - Code
     <?php
     $threshold = $argv[1] * 0.1;
     $a = array();
     $i = 0;
     do {
         if ($i <= $argv[1]) {
             $a[] = array($i, rand(1, 10));
             usort($a, 'priority_sort');
         }
         if ($i > $threshold) {
             array_shift($a);
         }
         $i++;
     } while (count($a));
     function priority_sort($a, $b) {
         return $a[1] - $b[1];
     }
SplPriorityQueue - Code (cont.)
   <?php
   $threshold = $argv[1] * 0.1;
   $a = new SplPriorityQueue;
   $i = 0;
   do {
        if ($i < 1) {
            $a->insert($i, rand(1,10));
        }
        if ($i > $threshold) {
            $a->extract();
        }
        $i++;
   } while (count($a));
SplPriorityQueue - EPS
SplPriorityQueue - Memory
The Set
The Composite Hash Map

    Just pretend the red pills are objects.
SplObjectStorage - What
 • Combination of two data structures
   – Composite hash map: a hash map with objects for
     keys; the spl_object_hash() function must be used
     for arrays to have this capability
   – Set: focuses on a group of values rather than
     individual values with operations like union,
     intersection, difference, and element_of; no
     concept of sequential order
 • Currently lacks a method for the intersection
   operation
SplObjectStorage - When

 • It’s best to use this when:
   – You need to store data using composite (i.e. non-
     scalar) keys
   – You need the ability to access data using set
     operations more so than accessing it in a
     particular order
SplObjectStorage - Code
 <?php
 $a = array();
 for ($i = 0; $i < $argv[1]; $i++) {
     $object = new stdClass;
     $a[spl_object_hash($object)] = $object;
 }
 $a = array();
 $b = array();
 for ($i = 0; $i < $argv[1]; $i++) {
     $a[] = rand(1, $argv[1]);
     $b[] = rand(1, $argv[1]);
 }
 $c = array_merge($a, $b);
 $c = array_diff($a, $b);
SplObjectStorage - Code (cont.)
 <?php
 $a = new SplObjectStorage;
 for ($i = 0; $i < $argv[1]; $i++) {
     $object = new stdClass;
     $a->attach($object, $object);
 }
 $a = new SplObjectStorage;
 $b = new SplObjectStorage;
 for ($i = 0; $i < $argv[1]; $i++) {
     $a->attach((object) rand(1, $argv[1]));
     $b->attach((object) rand(1, $argv[1]));
 }
 $c = clone $a;
 $c->addAll($b);
 $c = clone $a;
 $c->removeAll($b);
SplObjectStorage - EPS
SplObjectStorage - Memory
Thank this guy

 • Etienne Kneuss did a lot of the work on the
   new SPL features in PHP 5.3
Some great SPL resources

 • SPL in the PHP manual
 • Etienne Kneuss' blog
 • "SPL to the Rescue" by Elizabeth Smith
 • “SPL, a bridge not too far” by Michelangelo
   van Dam
 • This presentation as a blog post
Possible future SPL features

 • Graphs
   – Contain nodes and edges connecting them
   – Directional / non-directional
   – Cyclic / acyclic
   – Connected / unconnected
   – Edge costs
 • Trees
   – Acyclic unidirectional graph
   – Hierarchical in nature
Feedback, please!

     http://joind.in/1577
That’s all, folks

 •   Any questions?
 •   http://synacor.com
 •   http://matthewturland.com
 •   me@matthewturland.com
 •   @elazar on Twitter
 •   Elazar on the Freenode IRC network
1 of 62

Recommended

Spl Not A Bridge Too Far phpNW09 by
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Michelangelo van Dam
2K views57 slides
SPL: The Undiscovered Library - DataStructures by
SPL: The Undiscovered Library -  DataStructuresSPL: The Undiscovered Library -  DataStructures
SPL: The Undiscovered Library - DataStructuresMark Baker
5.3K views62 slides
Intro to The PHP SPL by
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPLChris Tankersley
5.8K views38 slides
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy by
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPatrick Allaert
20.8K views95 slides
PHP 7 – What changed internally? (Forum PHP 2015) by
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
7.5K views83 slides
PHP 7 – What changed internally? (PHP Barcelona 2015) by
PHP 7 – What changed internally? (PHP Barcelona 2015)PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
12.2K views88 slides

More Related Content

What's hot

Invertible-syntax 入門 by
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
2.3K views101 slides
Solr & Lucene @ Etsy by Gregg Donovan by
Solr & Lucene @ Etsy by Gregg DonovanSolr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanGregg Donovan
3K views84 slides
Metaprogramming in Haskell by
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
4.2K views156 slides
Electrify your code with PHP Generators by
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
3.7K views49 slides
Corephpcomponentpresentation 1211425966721657-8 by
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
491 views32 slides
DBIx::Class beginners by
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginnersleo lapworth
26.1K views95 slides

What's hot(20)

Invertible-syntax 入門 by Hiromi Ishii
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
Hiromi Ishii2.3K views
Solr & Lucene @ Etsy by Gregg Donovan by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanSolr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg Donovan
Gregg Donovan3K views
Metaprogramming in Haskell by Hiromi Ishii
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
Hiromi Ishii4.2K views
Electrify your code with PHP Generators by Mark Baker
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
Mark Baker3.7K views
Corephpcomponentpresentation 1211425966721657-8 by PrinceGuru MS
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS491 views
DBIx::Class beginners by leo lapworth
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
leo lapworth26.1K views
What's new in PHP 8.0? by Nikita Popov
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov3.2K views
PHP Functions & Arrays by Henry Osborne
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne3.2K views
Adventures in Optimization by David Golden
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
David Golden178 views
Manifests of Future Past by Puppet
Manifests of Future PastManifests of Future Past
Manifests of Future Past
Puppet1.6K views
PHP Unit 4 arrays by Kumar
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
Kumar 4.2K views
Perforce Object and Record Model by Perforce
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
Perforce256 views
DBIx::Class introduction - 2010 by leo lapworth
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
leo lapworth3.7K views

Similar to New SPL Features in PHP 5.3

UNIT IV (4).pptx by
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptxDrDhivyaaCRAssistant
16 views114 slides
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ... by
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
5 views114 slides
PHP and MySQL Tips and tricks, DC 2007 by
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
2.1K views39 slides
Internationalizing CakePHP Applications by
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
5.8K views18 slides
PHP tips and tricks by
PHP tips and tricks PHP tips and tricks
PHP tips and tricks Damien Seguy
13.4K views36 slides
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011 by
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
1.4K views24 slides

Similar to New SPL Features in PHP 5.3(20)

Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ... by Dhivyaa C.R
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R5 views
PHP and MySQL Tips and tricks, DC 2007 by Damien Seguy
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
Damien Seguy2.1K views
Internationalizing CakePHP Applications by Pierre MARTIN
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
Pierre MARTIN5.8K views
PHP tips and tricks by Damien Seguy
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
Damien Seguy13.4K views
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011 by camp_drupal_ua
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
camp_drupal_ua1.4K views
Php array by Nikul Shah
Php arrayPhp array
Php array
Nikul Shah5.3K views
PHP security audits by Damien Seguy
PHP security auditsPHP security audits
PHP security audits
Damien Seguy5.3K views
PHP Static Code Review by Damien Seguy
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
Damien Seguy1.1K views
9780538745840 ppt ch06 by Terry Yoast
9780538745840 ppt ch069780538745840 ppt ch06
9780538745840 ppt ch06
Terry Yoast253 views
Laravel collections an overview - Laravel SP by Matheus Marabesi
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SP
Matheus Marabesi481 views
Scaling php applications with redis by jimbojsb
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
jimbojsb17K views
Php Code Audits (PHP UK 2010) by Damien Seguy
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
Damien Seguy3K views

More from Matthew Turland

New SPL Features in PHP 5.3 (TEK-X) by
New SPL Features in PHP 5.3 (TEK-X)New SPL Features in PHP 5.3 (TEK-X)
New SPL Features in PHP 5.3 (TEK-X)Matthew Turland
4.8K views44 slides
Sinatra by
SinatraSinatra
SinatraMatthew Turland
783 views21 slides
Web Scraping with PHP by
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHPMatthew Turland
4.4K views52 slides
Web Scraping with PHP by
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHPMatthew Turland
2.8K views50 slides
Open Source Networking with Vyatta by
Open Source Networking with VyattaOpen Source Networking with Vyatta
Open Source Networking with VyattaMatthew Turland
1.2K views12 slides
When RSS Fails: Web Scraping with HTTP by
When RSS Fails: Web Scraping with HTTPWhen RSS Fails: Web Scraping with HTTP
When RSS Fails: Web Scraping with HTTPMatthew Turland
8.2K views46 slides

More from Matthew Turland(15)

New SPL Features in PHP 5.3 (TEK-X) by Matthew Turland
New SPL Features in PHP 5.3 (TEK-X)New SPL Features in PHP 5.3 (TEK-X)
New SPL Features in PHP 5.3 (TEK-X)
Matthew Turland4.8K views
Open Source Networking with Vyatta by Matthew Turland
Open Source Networking with VyattaOpen Source Networking with Vyatta
Open Source Networking with Vyatta
Matthew Turland1.2K views
When RSS Fails: Web Scraping with HTTP by Matthew Turland
When RSS Fails: Web Scraping with HTTPWhen RSS Fails: Web Scraping with HTTP
When RSS Fails: Web Scraping with HTTP
Matthew Turland8.2K views
Open Source Content Management Systems by Matthew Turland
Open Source Content Management SystemsOpen Source Content Management Systems
Open Source Content Management Systems
Matthew Turland913 views
Creating Web Services with Zend Framework - Matthew Turland by Matthew Turland
Creating Web Services with Zend Framework - Matthew TurlandCreating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew Turland
Matthew Turland6.7K views
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville by Matthew Turland
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake DevilleThe OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
Matthew Turland929 views
Utilizing the Xen Hypervisor in business practice - Bryan Fusilier by Matthew Turland
Utilizing the Xen Hypervisor in business practice - Bryan FusilierUtilizing the Xen Hypervisor in business practice - Bryan Fusilier
Utilizing the Xen Hypervisor in business practice - Bryan Fusilier
Matthew Turland958 views
The Ruby Programming Language - Ryan Farnell by Matthew Turland
The Ruby Programming Language - Ryan FarnellThe Ruby Programming Language - Ryan Farnell
The Ruby Programming Language - Ryan Farnell
Matthew Turland794 views
PDQ Programming Languages plus an overview of Alice - Frank Ducrest by Matthew Turland
PDQ Programming Languages plus an overview of Alice - Frank DucrestPDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
Matthew Turland962 views
Getting Involved in Open Source - Matthew Turland by Matthew Turland
Getting Involved in Open Source - Matthew TurlandGetting Involved in Open Source - Matthew Turland
Getting Involved in Open Source - Matthew Turland
Matthew Turland939 views

Recently uploaded

TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensorssugiuralab
19 views15 slides
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院IttrainingIttraining
41 views8 slides
1st parposal presentation.pptx by
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptxi238212
9 views3 slides
Info Session November 2023.pdf by
Info Session November 2023.pdfInfo Session November 2023.pdf
Info Session November 2023.pdfAleksandraKoprivica4
11 views15 slides
STPI OctaNE CoE Brochure.pdf by
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdfmadhurjyapb
13 views1 slide
The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
79 views25 slides

Recently uploaded(20)

TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab19 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
1st parposal presentation.pptx by i238212
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptx
i2382129 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb13 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada126 views
Case Study Copenhagen Energy and Business Central.pdf by Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 views
Black and White Modern Science Presentation.pptx by maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
maryamkhalid291616 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software257 views
handbook for web 3 adoption.pdf by Liveplex
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdf
Liveplex22 views
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
Empathic Computing: Delivering the Potential of the Metaverse by Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst476 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma31 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2217 views
From chaos to control: Managing migrations and Microsoft 365 with ShareGate! by sammart93
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!From chaos to control: Managing migrations and Microsoft 365 with ShareGate!
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!
sammart939 views

New SPL Features in PHP 5.3

  • 1. New SPL Features in PHP 5.3 Matthew Turland TEK-X May 20, 2010
  • 2. Hi! My name is… • Senior Platform Engineer for Synacor, Inc. • Former author and TE for php|architect • Author of Web Scraping with PHP • Past contributor to Zend Framework • Lead developer of Phergie • ULL alumni with a BS in computer science
  • 3. And I work for… • Provides internet solutions to ISPs, media companies, and advertisers • International company with offices in Buffalo, New York City, Los Angeles, and Amsterdam • Clientele includes most of the top 20 cable providers in the United States • Great company – join us!
  • 4. What about you? • Used the SPL before? • Using PHP 5.3? • Computer science background? • Knowledge of data structures?
  • 5. Pre-5.3 SPL Features • Classes: ArrayObject, SplFileInfo, SplSubject, SplObserver, etc. • Iterators: RecursiveIteratorIterator, FilterIterator, LimitIterator, etc. • Interfaces: ArrayAccess, Countable, Iterator, IteratorAggregate, etc. • Functions: spl_autoload_register, iterator_to_array, spl_object_hash, etc.
  • 6. Containers “A container is a class, a data structure, or an abstract data type whose instances are collections of other objects. They are used to store objects in an organized way following specific access rules.” Container (data structure) - Wikipedia
  • 7. Why containers? • We already have arrays and strings! array() 'string'
  • 8. Two excellent reasons • Versus traditional arrays, there is potential for: – Less CPU usage – Less memory usage
  • 9. Arrays are (not always) great • Flexible general purpose container • Underlying hash table algorithm is not always ideal for the task at hand
  • 10. Warning: Benchmarks Ahead • Lies, Outrageous Lies, and Benchmarks • PHP 5.3.2 compiled on Ubuntu 9.10 • Intel Core2Duo 1.83 GHz, 4 GB DDR2 RAM • Performance results are shown in executions per second rather than time per execution to avoid really small numbers • Code and results
  • 12. SplFixedArray - What • Like an array, but with a fixed length • Only allows integers >= 0 for keys • Can be resized, but at a cost • Not compatible with array functions
  • 13. SplFixedArray - When • It’s best to use this when: – You know in advance how many elements you want to store (e.g. mysql_num_rows) – You only need to access elements in sequential order
  • 14. SplFixedArray - Code <?php $a = array(); for ($i = 0; $i < $argv[1]; $i++) { $a[$i] = $i; $i = $a[$i]; } <?php $a = new SplFixedArray($argv[1]); for ($i = 0; $i < $argv[1]; $i++) { $a[$i] = $i; $i = $a[$i]; }
  • 17. SplDoublyLinkedList - What • Mainly intended as a parent class • Same unlimited size as arrays without the associated hash map algorithm • Less performance, but more memory efficiency
  • 18. SplDoublyLinkedList - When • It’s best to use this when: – You do not know in advance how many elements you want to store – You only need to access elements in sequential order
  • 19. SplDoublyLinkedList - Code <?php $a = array(); for ($i = 0; $i < $argv[1]; $i++) { $a[] = $i; $i = $a[$i]; } <?php $a = new SplDoublyLinkedList($argv[1]); for ($i = 0; $i < $argv[1]; $i++) { $a[] = $i; $i = $a[$i]; }
  • 23. SplStack - What • 2 operations – Push: [] for both array and SplStack – Pop: array_pop() vs SplStack::pop() • Last In, First Out (LIFO) – The last item pushed onto the top of the stack is the first item that will be popped off of the top of the stack
  • 24. SplStack - When • It’s best to use this when: – You do not know in advance how many elements you want to store – You only ever need to access the last element you stored
  • 25. SplStack - Code <?php $a = array(); for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { array_pop($a); }
  • 26. SplStack - Code (cont.) <?php $a = new SplStack; for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { $a->pop(); }
  • 30. SplQueue - What • 2 operations – Enqueue: [] for both array and SplQueue – Dequeue: array_shift() vs SplQueue::dequeue() • First In, First Out (FIFO) – The first item added to the end of the queue will be the first item removed from the front of the queue
  • 31. SplQueue - When • It’s best to use this when: – You do not know in advance how many elements you want to store – You only ever need to access the remaining element that was stored earliest
  • 32. SplQueue - Code <?php $a = array(); for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { array_shift($a); }
  • 33. SplQueue - Code (cont.) <?php $a = new SplQueue; for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { $a->dequeue(); }
  • 37. SplHeap - What • 2 operations – Insert: [] + sort vs SplHeap::insert() – Remove: array_shift() vs SplHeap::extract() • Internally reorders items based on comparison – SplHeap::compare() can be overridden • Subclasses – SplMinHeap – SplMaxHeap • Better worst-case scenario performance versus arrays (heap sort versus quick sort)
  • 38. SplHeap - When • It’s best to use this when: – You do not know in advance how many elements you want to store – You need to access elements in an order based on how they compare to each other
  • 39. SplMinHeap - Code <?php $a = array(); for($i = 0; $i < $argv[1]; $i++) { $a[] = rand(1, $argv[1]); sort($a); } for($i = 0; $i < $argv[1]; $i++) { array_shift($a); }
  • 40. SplMinHeap - Code (cont.) <?php $a = new SplMinHeap; for($i = 0; $i < $argv[1]; $i++) { $a->insert(rand(1, $argv[1])); } for($i = 0; $i < $argv[1]; $i++) { $a->extract(); }
  • 44. SplPriorityQueue - What • Accepts a priority with the element value • Element with highest priority comes out first • Priorities may be of any comparable type • SplPriorityQueue::compare() can be overridden • Operates similarly to a heap – In fact, it uses a heap internally for storage
  • 45. SplPriorityQueue - When • It’s best to use this when: – You do not know in advance how many elements you want to store – You need to access elements in an order based on how priority values associated with those elements compare to each other
  • 46. SplPriorityQueue - Code <?php $threshold = $argv[1] * 0.1; $a = array(); $i = 0; do { if ($i <= $argv[1]) { $a[] = array($i, rand(1, 10)); usort($a, 'priority_sort'); } if ($i > $threshold) { array_shift($a); } $i++; } while (count($a)); function priority_sort($a, $b) { return $a[1] - $b[1]; }
  • 47. SplPriorityQueue - Code (cont.) <?php $threshold = $argv[1] * 0.1; $a = new SplPriorityQueue; $i = 0; do { if ($i < 1) { $a->insert($i, rand(1,10)); } if ($i > $threshold) { $a->extract(); } $i++; } while (count($a));
  • 51. The Composite Hash Map Just pretend the red pills are objects.
  • 52. SplObjectStorage - What • Combination of two data structures – Composite hash map: a hash map with objects for keys; the spl_object_hash() function must be used for arrays to have this capability – Set: focuses on a group of values rather than individual values with operations like union, intersection, difference, and element_of; no concept of sequential order • Currently lacks a method for the intersection operation
  • 53. SplObjectStorage - When • It’s best to use this when: – You need to store data using composite (i.e. non- scalar) keys – You need the ability to access data using set operations more so than accessing it in a particular order
  • 54. SplObjectStorage - Code <?php $a = array(); for ($i = 0; $i < $argv[1]; $i++) { $object = new stdClass; $a[spl_object_hash($object)] = $object; } $a = array(); $b = array(); for ($i = 0; $i < $argv[1]; $i++) { $a[] = rand(1, $argv[1]); $b[] = rand(1, $argv[1]); } $c = array_merge($a, $b); $c = array_diff($a, $b);
  • 55. SplObjectStorage - Code (cont.) <?php $a = new SplObjectStorage; for ($i = 0; $i < $argv[1]; $i++) { $object = new stdClass; $a->attach($object, $object); } $a = new SplObjectStorage; $b = new SplObjectStorage; for ($i = 0; $i < $argv[1]; $i++) { $a->attach((object) rand(1, $argv[1])); $b->attach((object) rand(1, $argv[1])); } $c = clone $a; $c->addAll($b); $c = clone $a; $c->removeAll($b);
  • 58. Thank this guy • Etienne Kneuss did a lot of the work on the new SPL features in PHP 5.3
  • 59. Some great SPL resources • SPL in the PHP manual • Etienne Kneuss' blog • "SPL to the Rescue" by Elizabeth Smith • “SPL, a bridge not too far” by Michelangelo van Dam • This presentation as a blog post
  • 60. Possible future SPL features • Graphs – Contain nodes and edges connecting them – Directional / non-directional – Cyclic / acyclic – Connected / unconnected – Edge costs • Trees – Acyclic unidirectional graph – Hierarchical in nature
  • 61. Feedback, please! http://joind.in/1577
  • 62. That’s all, folks • Any questions? • http://synacor.com • http://matthewturland.com • me@matthewturland.com • @elazar on Twitter • Elazar on the Freenode IRC network