Who is this article for?
Anyone looking for how to convert an adjacency set to a nested JSON response. Different types of data can be stored as adjacency set e.x. Menu items, any kind of hierarchy, etc.
In this article, I’m going to walk through on a couple of algorithms written in PHP.
Before You Begin
We will be utilizing the data definition and structure from this article - MySQL – Adjacency List Model For Hierarchical Data Using CTE. You can refer to this post to create the MySQL Table and populate data.
For performance comparison, I am going to use blackfire.io. We will be ignoring the performance of all other components like MySQL except for
To get more accurate results, I am going to use several sample size, in this case, I used 10.
|#||EXECUTION TIME||I/O WAIT TIME||CPU||PEAK MEMORY|
|Method 1||734 µs||376 µs||358 µs||44.2 kB|
|Method 2||762 µs||392 µs||371 µs||44.8 kB|
Recursive Calls for
|#||TOTAL DB RECORDS||CALLS FOR
As you can see both Method 1 and Method 2 generates the same output. These can be used with any type of dataset. It performs recursive operations and produces output for any depth of data.
Although, we don't really see the benefit of using Method 2 over Method 1 as the data set used is very small. The difference in performance is almost similar for small dataset.
But, I would strongly recommend using Method 2, as this method is far more superior and faster.
In my next article, we will dive deep into comparing the performance of these two methods.