Array sorting in Front-end or Back-end

edash picture edash · Apr 14, 2017 · Viewed 11k times · Source

I am implementing a RESTful API that returns an array. I want to know if it will be more efficient to sort the array in descending order in my backend code or in the javascript?

Answer

Andre T picture Andre T · Apr 14, 2017

Your API will be used by n clients. Performance-wise it would make sense to have each client do the sorting on their own instead of having the server do it for all the n clients. Simply, less CPU work for the server.

Furthermore, whether the result needs to be sorted or not depends on the nature of the application using the data. Let the application decide that. Some interfaces allow the user to decide what to sort by, thereby convenient to do it locally (without waiting for a background HTTP call).

However I would not overthink the performance part before you actually have a performance problem. It could also be that the data sorting is not really costly or the sorting has already been done depending on how information is kept internally (in DBMS-s, for example).

Edit

With up to 20 rows without sorting, it really makes no important difference - make the API implementing developers' life easier and do the small sorting on the frontend side.