Search code examples
javascriptalgorithmtime-complexity

What is time complexity when using object for sorting?


I have a socket with realtime values. I get the unsorted row object then I need to create a list of the received objects and sort them by price. After this, my data is sorted correctly. I am using object for this problem. like this:

const data={};
function createListAndSort(row){
  data[row.price]=row;
  return Object.values(data); // return sorted data   
}

socket.onMessage=(row)=>{
  createListAndSort(row)
}


My row data is real time but this have three property like this:

row = {id: 1 , price: 15664, name: 'test'}

In this method, although the values are entered in a specific order, they are automatically sorted into the object due to the number of the keys. like this: enter image description here

As mentioned, the received data are not sorted and may reach us in any order. And that the output data were also sorted with this method. I need to know if the time complexity of this method is less or using the sort function. what is auto sort time complexity in object?


Solution

  • Using objects for tabular/list data isn't optimal. You miss all array methods you could utilize to manipulate your data. Always use arrays. For your case just collect rows in an array and sort by the price property. While pushing items into an object to get them sorted is faster, on real-case data size the benefit is rather questionable.

    Regarding your case the algorithm is implementation specific, a black box. My guess it's a binary search + insert which is O(log N).

    Regarding your question in the comment

    I need to know if the time complexity of this method is less or the sorting function?

    My guess is yes, since the object property insert algorithm knows already that the property keys are sorted while the array sort func doesn't have this information.