SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
SPL Data Structures and their Complexity
                 Jurri¨n Stutterheim
                      e
                  September 17, 2011




1
1. Introduction




2
This presentation                                 §1




         Understand what data structures are
         How they are represented internally
         How “fast” each one is and why that is




3
Data structures                                                      §1




         Classes that offer the means to store and retrieve data,
         possibly in a particular order
         Implementation is (often) optimised for certain use cases
         array is PHP’s oldest and most frequently used data
         structure
         PHP 5.3 adds support for several others




4
Current SPL data structures    §1




         SplDoublyLinkedList
         SplStack
         SplQueue
         SplHeap
         SplMaxHeap
         SplMinHeap
         SplPriorityQueue
         SplFixedArray
         SplObjectStorage




5
Why care?                                                         §1




        Using the right data structure in the right place could
        improve performance
        Already implemented and tested: saves work
        Can add a type hint in a function definition
        Adds semantics to your code




6
Algorithmic complexity                                             §1




         We want to be able to talk about the performance of the
         data structure implementation
             Running speed (time complexity)
             Space consumption (space complexity)
         We describe complexity in terms of input size, which is
         machine and programming language independent




7
Example                                                          §1




      for ($i = 0; $i < $n; $i++) {
        for ($j = 0; $j < $n; $j++) {
          echo ’tick’;
        }
      }

     For some n, how many times is “tick” printed? I.e. what is the
     time complexity of this algorithm?




8
Example                                                          §1




      for ($i = 0; $i < $n; $i++) {
        for ($j = 0; $j < $n; $j++) {
          echo ’tick’;
        }
      }

     For some n, how many times is “tick” printed? I.e. what is the
     time complexity of this algorithm?
     n2 times




8
Talking about complexity                                                §1




         Pick a function to act as boundary for the algorithm’s
         complexity
         Worst-case
             Denoted O (big-Oh)
             “My algorithm will not be slower than this function”
         Best-case
             Denoted Ω (big-Omega)
             “My algorithm will at least be as slow as this function”
         If they are the same, we write Θ (big-Theta)
         In example: both cases are n2 , so the algorithm is in Θ(n2 )




9
Visualized   §1




10
Example 2                                             §1



      for ($i = 0; $i < $n; $i++) {
        if ($myBool) {
          for ($j = 0; $j < $n; $j++) {
            echo ’tick’;
          }
        }
      }

     What is the time complexity of this algorithm?




11
Example 2                                             §1



      for ($i = 0; $i < $n; $i++) {
        if ($myBool) {
          for ($j = 0; $j < $n; $j++) {
            echo ’tick’;
          }
        }
      }

     What is the time complexity of this algorithm?

         O(n2 )
         Ω(n) (if $myBool is false)
         No Θ!

11
We can be a bit sloppy                                              §1



      for ($i = 0; $i < $n; $i++) {
        if ($myBool) {
          for ($j = 0; $j < $n; $j++) {
            echo ’tick’;
          }
        }
      }


         We describe algorithmic behaviour as input size grows to
         infinity
             constant factors and smaller terms don’t matter too much
         E.g. 3n2 + 4n + 1 is in O(n2 )


12
Other functions                            §1




       for ($i = 0; $i < $n; $i++) {
         for ($j = 0; $j < $n; $j++) {
           echo ’tick’;
         }
       }

       for ($i = 0; $i < $n; $i++) {
         echo ’tock’;
       }

      This algorithm is still in Θ(n2 ).



13
Bounds                                                    §1




                               Figure: Order relations1




         1
14           Taken from Cormen et al. 2009
Complexity Comparison                                                                 §1

           3
      10
                                        Superexponential   Factorial   Exponential




                                                                          Quadratic
      102




                                                                              Linear
           1
      10




                                                                         Logarithmic
       100




                                                                                     101
     Constant: 1, logarithmic: lg n, linear: n, quadratic: n2 ,
     exponential: 2n , factorial: n!, super-exponential: nn

15
In numbers                            §1



     Approximate growth for n = 50:

               1 1
             lg n 5.64
               n 50
              n2 2500
              n3 12500
              2n 1125899906842620
              n! 3.04 ∗ 1064
              nn 8.88 ∗ 1084



16
Some more notes on complexity                                     §1




        Constant time is written 1, but goes for any constant c
        Polynomial time contains all functions in nc for some
        constant c
        Everything in this presentation will be in polynomial time




17
2. SPL Data Structures




18
Credit where credit is due                                         §2




      The first three pictures in this section are from Wikipedia




19
SplDoublyLinkedList                                                  §2



                 12                99                37


         Superclass of SplStack and SplQueue
         SplDoublyLinkedList is not truly a doubly linked list; it
         behaves like a hashtable




20
SplDoublyLinkedList                                                  §2



                 12                99                37


         Superclass of SplStack and SplQueue
         SplDoublyLinkedList is not truly a doubly linked list; it
         behaves like a hashtable
         Usual doubly linked list time complexity
             Append/prepend to available node in Θ(1)
             Lookup by scanning in O(n)
             Access to beginning/end in Θ(1)




20
SplDoublyLinkedList                                                  §2



                 12                99                37


         Superclass of SplStack and SplQueue
         SplDoublyLinkedList is not truly a doubly linked list; it
         behaves like a hashtable
         Usual doubly linked list time complexity
             Append/prepend to available node in Θ(1)
             Lookup by scanning in O(n)
             Access to beginning/end in Θ(1)
         SplDoublyLinkedList time complexity
             Insert/delete by index in Θ(1)
             Lookup by index in Θ(1)
             Access to beginning/end in Θ(1)

20
SplStack                                                         §2


           Subclass of SplDoublyLinkedList; adds no new operations
           Last-in, first-out (LIFO)
           Pop/push value from/on the top of the stack in Θ(1)




                           Push          Pop




21
SplQueue                                                           §2

           Subclass of SplDoublyLinkedList; adds enqueue/dequeue
           operations
           First-in, first-out (FIFO)
           Read/dequeue element from front in Θ(1)
           Enqueue element to the end in Θ(1)



                         Enqueue




                                       Dequeue


22
Short excursion: trees                                        §2


                                             100




                                        19         36




                               17       3          25   1




                           2        7




         Consists of nodes (vertices) and directed edges
         Each node always has in-degree 1
             Except the root: always in-degree 0
         Previous property implies there are no cycles
         Binary tree: each node has at most two child-nodes
23
SplHeap, SplMaxHeap and SplMinHeap                                §2


                                            100




                                       19         36




                              17       3          25   1




                          2        7




        A heap is a tree with the heap property : for all A and B, if
        B is a child node of A, then
            val(A)    val(B) for a max-heap: SplMaxHeap
            val(A)    val(B) for a min-heap: SplMinHeap
        Where val(A) denotes the value of node A
24
Heaps contd.                                §2




        SplHeap is an abstract superclass
        Implemented as binary tree
        Access to root element in Θ(1)
        Insertion/deletion in O(lg n)




25
SplPriorityQueue                                                   §2




         Variant of SplMaxHeap: for all A and B, if B is a child
         node of A, then prio(A) prio(B)
         Where prio(A) denotes the priority of node A




26
SplFixedArray                                           §2




         Fixed-size array with numerical indices only
         Efficient OO array implementation
             No hashing required for keys
             Can make assumptions about array size
         Lookup, insertion, deletion in Θ(1) time
         Resize in Θ(n)




27
SplObjectStorage                                    §2




         Storage container for objects
         Insertion, deletion in Θ(1)
         Verification of presence in Θ(1)
         Missing: set operations
             Union, intersection, difference, etc.




28
3. Concluding




29
Missing in PHP                                                     §3




        Set data structure
        Map/hashtable data structure
            Does SplDoublyLinkedList satisfy this use case?
            If yes: split it in two separate structures and make
            SplDoublyLinkedList a true doubly linked list
        Immutable data structures
            Allows us to more easily emulate “pure” functions
            Less bugs in your code due to lack of mutable state




30
Closing remarks                                §3




         Use the SPL data structures!
         Choose them with care
         Reason about your code’s complexity




31
Questions         §3




     Questions?




32

Más contenido relacionado

La actualidad más candente

Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Knowledge engg using & in fol
Knowledge engg using & in folKnowledge engg using & in fol
Knowledge engg using & in folchandsek666
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode CompilerDonal Fellows
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Structure and interpretation of computer programs modularity, objects, and ...
Structure and interpretation of computer programs   modularity, objects, and ...Structure and interpretation of computer programs   modularity, objects, and ...
Structure and interpretation of computer programs modularity, objects, and ...bdemchak
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVMMario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1Dhaval Dalal
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Pj01 4-operators and control flow
Pj01 4-operators and control flowPj01 4-operators and control flow
Pj01 4-operators and control flowSasidharaRaoMarrapu
 

La actualidad más candente (20)

Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Knowledge engg using & in fol
Knowledge engg using & in folKnowledge engg using & in fol
Knowledge engg using & in fol
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Structure and interpretation of computer programs modularity, objects, and ...
Structure and interpretation of computer programs   modularity, objects, and ...Structure and interpretation of computer programs   modularity, objects, and ...
Structure and interpretation of computer programs modularity, objects, and ...
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1
 
Computer Programming- Lecture 4
Computer Programming- Lecture 4Computer Programming- Lecture 4
Computer Programming- Lecture 4
 
recursion2
recursion2recursion2
recursion2
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Pj01 4-operators and control flow
Pj01 4-operators and control flowPj01 4-operators and control flow
Pj01 4-operators and control flow
 

Similar a Pf congres20110917 data-structures

19 algorithms-and-complexity-110627100203-phpapp02
19 algorithms-and-complexity-110627100203-phpapp0219 algorithms-and-complexity-110627100203-phpapp02
19 algorithms-and-complexity-110627100203-phpapp02Muhammad Aslam
 
Complexity analysis - The Big O Notation
Complexity analysis - The Big O NotationComplexity analysis - The Big O Notation
Complexity analysis - The Big O NotationJawad Khan
 
Insertion sort and shell sort
Insertion sort and shell sortInsertion sort and shell sort
Insertion sort and shell sortPraveen Kumar
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developersbrweber2
 
Basic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV SyllabusBasic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV SyllabusNANDINI SHARMA
 
GPUVerify - Implementation
GPUVerify - ImplementationGPUVerify - Implementation
GPUVerify - Implementationgedgemaster
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysischidabdu
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues listsJames Wong
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
StacksqueueslistsFraboni Ec
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsYoung Alista
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsTony Nguyen
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsHarry Potter
 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfAmayJaiswal4
 

Similar a Pf congres20110917 data-structures (20)

19 algorithms-and-complexity-110627100203-phpapp02
19 algorithms-and-complexity-110627100203-phpapp0219 algorithms-and-complexity-110627100203-phpapp02
19 algorithms-and-complexity-110627100203-phpapp02
 
Complexity analysis - The Big O Notation
Complexity analysis - The Big O NotationComplexity analysis - The Big O Notation
Complexity analysis - The Big O Notation
 
Introduction to Erlang
Introduction to ErlangIntroduction to Erlang
Introduction to Erlang
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
 
Insertion sort and shell sort
Insertion sort and shell sortInsertion sort and shell sort
Insertion sort and shell sort
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
CODEsign 2015
CODEsign 2015CODEsign 2015
CODEsign 2015
 
Basic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV SyllabusBasic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV Syllabus
 
AA_Unit 1_part-I.pptx
AA_Unit 1_part-I.pptxAA_Unit 1_part-I.pptx
AA_Unit 1_part-I.pptx
 
GPUVerify - Implementation
GPUVerify - ImplementationGPUVerify - Implementation
GPUVerify - Implementation
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
Stacksqueueslists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Clojure
ClojureClojure
Clojure
 
ICSM07.ppt
ICSM07.pptICSM07.ppt
ICSM07.ppt
 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdf
 

Último

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Último (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Pf congres20110917 data-structures

  • 1. SPL Data Structures and their Complexity Jurri¨n Stutterheim e September 17, 2011 1
  • 3. This presentation §1 Understand what data structures are How they are represented internally How “fast” each one is and why that is 3
  • 4. Data structures §1 Classes that offer the means to store and retrieve data, possibly in a particular order Implementation is (often) optimised for certain use cases array is PHP’s oldest and most frequently used data structure PHP 5.3 adds support for several others 4
  • 5. Current SPL data structures §1 SplDoublyLinkedList SplStack SplQueue SplHeap SplMaxHeap SplMinHeap SplPriorityQueue SplFixedArray SplObjectStorage 5
  • 6. Why care? §1 Using the right data structure in the right place could improve performance Already implemented and tested: saves work Can add a type hint in a function definition Adds semantics to your code 6
  • 7. Algorithmic complexity §1 We want to be able to talk about the performance of the data structure implementation Running speed (time complexity) Space consumption (space complexity) We describe complexity in terms of input size, which is machine and programming language independent 7
  • 8. Example §1 for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { echo ’tick’; } } For some n, how many times is “tick” printed? I.e. what is the time complexity of this algorithm? 8
  • 9. Example §1 for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { echo ’tick’; } } For some n, how many times is “tick” printed? I.e. what is the time complexity of this algorithm? n2 times 8
  • 10. Talking about complexity §1 Pick a function to act as boundary for the algorithm’s complexity Worst-case Denoted O (big-Oh) “My algorithm will not be slower than this function” Best-case Denoted Ω (big-Omega) “My algorithm will at least be as slow as this function” If they are the same, we write Θ (big-Theta) In example: both cases are n2 , so the algorithm is in Θ(n2 ) 9
  • 11. Visualized §1 10
  • 12. Example 2 §1 for ($i = 0; $i < $n; $i++) { if ($myBool) { for ($j = 0; $j < $n; $j++) { echo ’tick’; } } } What is the time complexity of this algorithm? 11
  • 13. Example 2 §1 for ($i = 0; $i < $n; $i++) { if ($myBool) { for ($j = 0; $j < $n; $j++) { echo ’tick’; } } } What is the time complexity of this algorithm? O(n2 ) Ω(n) (if $myBool is false) No Θ! 11
  • 14. We can be a bit sloppy §1 for ($i = 0; $i < $n; $i++) { if ($myBool) { for ($j = 0; $j < $n; $j++) { echo ’tick’; } } } We describe algorithmic behaviour as input size grows to infinity constant factors and smaller terms don’t matter too much E.g. 3n2 + 4n + 1 is in O(n2 ) 12
  • 15. Other functions §1 for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { echo ’tick’; } } for ($i = 0; $i < $n; $i++) { echo ’tock’; } This algorithm is still in Θ(n2 ). 13
  • 16. Bounds §1 Figure: Order relations1 1 14 Taken from Cormen et al. 2009
  • 17. Complexity Comparison §1 3 10 Superexponential Factorial Exponential Quadratic 102 Linear 1 10 Logarithmic 100 101 Constant: 1, logarithmic: lg n, linear: n, quadratic: n2 , exponential: 2n , factorial: n!, super-exponential: nn 15
  • 18. In numbers §1 Approximate growth for n = 50: 1 1 lg n 5.64 n 50 n2 2500 n3 12500 2n 1125899906842620 n! 3.04 ∗ 1064 nn 8.88 ∗ 1084 16
  • 19. Some more notes on complexity §1 Constant time is written 1, but goes for any constant c Polynomial time contains all functions in nc for some constant c Everything in this presentation will be in polynomial time 17
  • 20. 2. SPL Data Structures 18
  • 21. Credit where credit is due §2 The first three pictures in this section are from Wikipedia 19
  • 22. SplDoublyLinkedList §2 12 99 37 Superclass of SplStack and SplQueue SplDoublyLinkedList is not truly a doubly linked list; it behaves like a hashtable 20
  • 23. SplDoublyLinkedList §2 12 99 37 Superclass of SplStack and SplQueue SplDoublyLinkedList is not truly a doubly linked list; it behaves like a hashtable Usual doubly linked list time complexity Append/prepend to available node in Θ(1) Lookup by scanning in O(n) Access to beginning/end in Θ(1) 20
  • 24. SplDoublyLinkedList §2 12 99 37 Superclass of SplStack and SplQueue SplDoublyLinkedList is not truly a doubly linked list; it behaves like a hashtable Usual doubly linked list time complexity Append/prepend to available node in Θ(1) Lookup by scanning in O(n) Access to beginning/end in Θ(1) SplDoublyLinkedList time complexity Insert/delete by index in Θ(1) Lookup by index in Θ(1) Access to beginning/end in Θ(1) 20
  • 25. SplStack §2 Subclass of SplDoublyLinkedList; adds no new operations Last-in, first-out (LIFO) Pop/push value from/on the top of the stack in Θ(1) Push Pop 21
  • 26. SplQueue §2 Subclass of SplDoublyLinkedList; adds enqueue/dequeue operations First-in, first-out (FIFO) Read/dequeue element from front in Θ(1) Enqueue element to the end in Θ(1) Enqueue Dequeue 22
  • 27. Short excursion: trees §2 100 19 36 17 3 25 1 2 7 Consists of nodes (vertices) and directed edges Each node always has in-degree 1 Except the root: always in-degree 0 Previous property implies there are no cycles Binary tree: each node has at most two child-nodes 23
  • 28. SplHeap, SplMaxHeap and SplMinHeap §2 100 19 36 17 3 25 1 2 7 A heap is a tree with the heap property : for all A and B, if B is a child node of A, then val(A) val(B) for a max-heap: SplMaxHeap val(A) val(B) for a min-heap: SplMinHeap Where val(A) denotes the value of node A 24
  • 29. Heaps contd. §2 SplHeap is an abstract superclass Implemented as binary tree Access to root element in Θ(1) Insertion/deletion in O(lg n) 25
  • 30. SplPriorityQueue §2 Variant of SplMaxHeap: for all A and B, if B is a child node of A, then prio(A) prio(B) Where prio(A) denotes the priority of node A 26
  • 31. SplFixedArray §2 Fixed-size array with numerical indices only Efficient OO array implementation No hashing required for keys Can make assumptions about array size Lookup, insertion, deletion in Θ(1) time Resize in Θ(n) 27
  • 32. SplObjectStorage §2 Storage container for objects Insertion, deletion in Θ(1) Verification of presence in Θ(1) Missing: set operations Union, intersection, difference, etc. 28
  • 34. Missing in PHP §3 Set data structure Map/hashtable data structure Does SplDoublyLinkedList satisfy this use case? If yes: split it in two separate structures and make SplDoublyLinkedList a true doubly linked list Immutable data structures Allows us to more easily emulate “pure” functions Less bugs in your code due to lack of mutable state 30
  • 35. Closing remarks §3 Use the SPL data structures! Choose them with care Reason about your code’s complexity 31
  • 36. Questions §3 Questions? 32