Use of PHP7.2 Data Structures
This article mainly introduces the use of PHP7.2 Data Structures, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
PHP7.2 Data Structures use
1. Installation
pecl install ds
brew install homebrew/php/php71-ds
Currently PHP7.2 does not support installation using brew.
2. PHP original data structure Array
In the era of PHP5.x, Array
is the only data type that represents a collection in PHP , he is both List and Map, he is everything.
<?php $a = array(1,2,3,4); $b = array('a'=>1,'b'=>2,'c'=>3);
This data type does bring convenience to developers, but it allows PHPer to ignore the benefits of the data structure, especially when learning other languages. Troubled.
After PHP was upgraded to 7, Array
was also optimized, but its structure did not change, "optimized for everything; optimized for nothing" with room for improvement. So if we can optimize performance by introducing more convenient data structures, and writing code will be more convenient at the same time, then why not?
"What about SPL data structures?"
Unfortunately they are terrible. They did offer some benefits prior to PHP 7, but have since been neglected to the point of having no practical value.“Why can’t we fix and improve them?”
We could, but I believe their design and implementation is so poor that it would be better to replace them with something brand new.“The design of SPL data structures is terrible.” - Anthony Ferrara
Array
PHP's Array can get null when accessing a non-existent key, and no fatal error will occur, but there will be an E_NOTICE. This E_NOTICE will be intercepted by the function registered by set_error_handler. Obviously, this kind of unclean code and unnecessary performance overhead can be completely avoided.
<?php $a = []; $a['a']; // PHP Notice: Undefined offset
General PHPer will not use array_key_exists and if else to handle it, which will be a bit troublesome.
Sometimes when using Array, the performance will become very poor. Array is essentially a Map. Unshifting an element will change the key of each element. This is an O(n) operation. In addition, PHP's Array saves its value (including key and its hash) in a bucket, so we need to check each bucket and update the hash.
PHP internally completes the array_unshift operation by creating a new array, and the performance issues can be imagined.
DataStructures, an extension of PHP7, a replacement for array (Array).
Github: https://github.com/php-ds
Namespace: Ds\
Interface class: Collection, Sequence, Hashable
Implementation class (final class): Vector, Deque, Map, Set, Stack, Queue, PriorityQueue, Pair
Interface class
Collection is a basic interface that defines the basic operations of a data collection (the collection here refers to Collection, not Set) , such as foreach, echo, count, print_r, var_dump, serialize, json_encode, and clone. etc.
Sequence is the basic interface of array-like data structures and defines many important and convenient methods, such as contains, map, filter, reduce, find, first, last, etc. As can be seen from the figure, Vector, Deque, Stack, and Queue all directly or indirectly implement this interface. Its characteristics are as follows:
The value will always be indexed [0, 1, 2, …, size - 1]
Deletion or insertion updates the position of all consecutive values.
Only allows access to values with indexes in [0, size-1].
#Hashable looks isolated in the diagram, but is important for Maps and Sets. If an Object implements Hashable, it can be used as the key of Map and the element of Set. In this way, Map and Set can be used as conveniently as Java.
Implementation class
Vector should be one of the most commonly used data structures. You can think of it as Ruby's Array or Python's List. The index of its element's value is its index in the buffer, so it is very efficient. You can use it as long as you need to use an array and do not need insert, remove, shift and unshift.
Video description
The main data structure used in PhotoShop is Vector ---- Sean Parent
- ##The complexity of insert, remove, shift, and unshift is O(n)
- Low memory usage ##get, set , the complexity of push and pop is O(1)
- Advantages:
- Disadvantages:
- Deque (pronounced [dek]) is a "double-ended queue". A head pointer is added to the queue, so shift and unshift are also O(1) complex. But the performance loss is not much.
- Two pointers are used to track the head and tail. The pointers can be "wrap around" the end of the buffer, which avoids the need to move other values to make room. This makes shift and shift very fast - Vector can't compete with that. Video Description
- The buffer capacity must be 2 to the nth power.
- Low memory usage.
- The complexity of get,set, push, pop, shift, and unshift is O(1).
- Advantages:
- Disadvantages:
- Stack is a "LIFO" structure, according to The "last in, first out" principle allows accessing, traversing, and destroying the values at the top of the structure. DsStack internally uses the implementation of DsVector.
- Queue is a "FIFO" structure that allows access, traversal, and destruction of the values at the top of the structure according to the "first in, first out" principle. DsQueue internally uses the implementation of DsDeque.
- PriorityQueue (Priority Queue) is very similar to Queue. Values are pushed into the queue according to the assigned priority. The value with the highest priority is always at the front of the queue. Traversing the PriorityQueue is destructive and amounts to continuous pop operations until the queue is empty.
- Use maximum heap implementation
.
Hashable , an interface that allows objects to be used as keys. Note: It is not - hashTable
. Hashable only introduces two methods: hash and equals. The data structures that support the Hashable interface are Map and Set.
Map , a continuous collection of key-value pairs. It is consistent with the use of array. The key can be of any type, but it must be unique. If the same key is added to the Map, the original one will be replaced. Like array, insertion order is preserved. - When the size of the Map drops to a small enough size, it will be automatically released Allocated memory.
- key and value can be of any type, even objects.
- The complexity of put, get, remove, and hasKey is O(1)
- Disadvantages:
- If the value is deleted before indexing, the complexity will be From O(1) to O(n)
- Interface using Hashable
- Supports any type of value.
- Disadvantages:
- The complexity of insert and remove is O(n).
- When key is an object, it cannot be converted to Array.
- Efficiency and memory usage are almost the same as Array
- Advantages:
- Does not support push, pop, insert, shift, unshift
- Adding, deleting, and referencing are all O(1) complexity
- Advantages:
, it is a linear search with a complexity of O(n). If you want to create an array of unique values, you can use
array_unique()
. Since array_unique()
targets value rather than key, each array member will be restricted. Searching, the complexity will become O(n²). The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
How to compile and install extended redis and swoole in phpService container and dependency injection in PHP AnalysisThe above is the detailed content of Use of PHP7.2 Data Structures. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
