pecl install ds
brew install homebrew/php/php71-ds
目前PHP7.2不支持使用 brew 安裝。php
Array
PHP5.x 的時代,Array
是惟一的表示集合的數據類型,在 PHP 中,他既是 List 也是 Map, 他就是一切。前端
<?php $a = array(1,2,3,4); $b = array('a'=>1,'b'=>2,'c'=>3);
這種數據類型的確是給開發者帶來了便捷性,但讓PHPer 會主鍵的忽略掉數據結構帶來的好處,特別是在學習其餘的語言時,給PHPer 帶來困擾。git
在 PHP 升級到7後,Array
也同時獲得了優化,可是他的結構並無發生變化, 「optimised for everything; optimised for nothing」 with room for improvement。那若是咱們能夠經過引入更便利的數據結構優化性能,同時寫代碼反而更方便了,那何樂而不爲呢?github
「SPL數據結構怎麼樣?」
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.「咱們爲何不能修正和改進它們?」
We could, but I believe their design and implementation is so poor that it would be better to replace them with something brand new.shell「SPL數據結構的設計很是可怕。」 - 安東尼 費拉拉json
<?php $a = []; $a['a']; // PHP Notice: Undefined offset
通常的 PHPer 都不會用array_key_exists 和 if else 來處理,這樣作會顯得有些麻煩。vim
PHP 內部實際上是經過建立新的 array 來完成 array_unshift 操做的,其性能問題可想可知。數組
DataStructures,PHP7的一個擴展,數組(Array)的一個替代品。php7
Github: https://github.com/php-ds數據結構
Namespace: Ds\
接口類: Collection, Sequence, Hashable
實現類(final class): Vector, Deque, Map, Set, Stack, Queue, PriorityQueue, Pair
Sequence 是類數組數據結構的基礎接口,定義了不少重要且方便的方法,好比 contains, map, filter, reduce, find, first, last 等。從圖中可知,Vector, Deque, Stack, Queue 都直接或者間接的實現了這個接口。它的特色以下:
優勢:
缺點:
PhotoShop中使用主要的數據結構就是 Vector ---- Sean Parent
兩個指針用於跟蹤頭部和尾部, 指針能夠「wrap around」緩衝區的末尾,這避免了須要移動其餘值來騰出空間。 這使得移位和移位很是快 - Vector沒法與之競爭。視頻說明
優勢:
缺點:
hashTable
。Hashable只引入了兩種方法:hash和equals。支持Hashable接口的數據結構是Map和Set。Map , 一種連續的鍵值對集合。同 array 的使用是一致的,key 但是是任意的類型,可是必須惟一。若是相同的 key 添加到 Map 中,那麼會替換掉原有的。同array 同樣,插入的順序會被保留。
優勢:
缺點:
Set,是一個無序惟一值的集合。Map 內部使用了 set 的實現,他們都是基於Array 相同的內部結構,這意味這Set 的排序具備 O(n*log n) 的複雜度。
優勢:
缺點:
這裏在說明一點,Array中的值自己是沒有索引的,所以在使用 in_array()
的時候呈線性搜索,複雜度爲 O(n)。
若是想要建立一個惟一值數組,可使用 array_unique()
,因爲array_unique()
針對的是 value 而不是 key,因此每一個數組成員都會被限行搜索,複雜度會變爲 O(n²)。