Search code examples
phparrayssortingsortedlist

sorted array in php


in many languages like c#, java, etc, we have sorted array! it mean when we add some element to it, it will add new element in correct index base on sorting method ... with this algorithm inserting and element is too fast !

but in php as i know, we can just sort array with ksort,sort or something like that and i did't find something like sorted array in php for better performance in managing one array that we want always be sorted!

in my tough if i figure out how ksort works, i could write sorted array myself but i did't find any solution to add item to array by index ...

does anyone know how to implement sorted array in php ? Or does anyone know how to add element in any index i want?


update 1

i need something like this in php : https://www.tutorialsteacher.com/csharp/csharp-sortedlist

i have huge array (about 2m rows) and i should keep it sorted base on something like price !

for now i sorting it by ksort but i cause me huge impact on performance


Update 2

i want to create trade matching engine for my crypto currency exchange and for now i using redis as my data entry but when i used in php array as my data entry, performance increase about 250x.

(in redis i can add orders about 3.5k/s)

i tested my code and figured out that ksrot take about 83% of my code runtime. now i want to use sorted list as i say for improving my performance. for now i can handle about 930k/s orders(add in array , sort array, iterate top of array) with ksort.


Solution

  • finally i found the solution and it was: Priority Queue in SPL EXT https://www.php.net/manual/en/class.splpriorityqueue.php

    you can pass your compare method to it and it will store it sorted!

    i will create some sort of benchmark for compare using usort and priority queue solution for more accurate decision :)

    tnx @PtrTron for suggestion this