We need list of cities in alphabetic order to a client.
Should we cache the list as it is returned from the database (not sorted) OR cache it after sorting the list (as it would be returned to the client)?
We need list of cities in alphabetic order to a client.
Should we cache the list as it is returned from the database (not sorted) OR cache it after sorting the list (as it would be returned to the client)?
2
Answers
You should always do you sorting server side where possible. (See Here)
Then return the sorted list so the hard work is done. You then need to decide if the information should be cached or not. Caching allows access to data quicker then calling the server/database every time.
The problem with caching is you are not getting new/fresh data every call. You therefore need to decide if this list is being updated often or not.
If it is a drop down list on a form they fill regularly then cache.
If it is a register form they use once never again, don’t bother caching.
As mentioned, it’s best to sort in the database. That aside, assuming it is not sorted by the database, should you sort it and then cache it or cache it unsorted and sort it each time you retrieve it from the cache?
You should sort it before putting it in the cache. Think of the cache as not just storing data but storing work. The work of providing the list of cities to the client includes retrieving it from the database and sorting it.
This is true whether a process involves retrieving data from a database or some external API or even if it requires some long-running process that’s internal to the application. Instead of just data the process might produce some objects containing the results of that work. It’s up to you to determine whether something should be cached and for how long. But in general it’s worth considering whether you can cache the output of the entire process vs. just the data retrieval.
You can also cache parts of a process. Suppose, for example, you have a call that returns the real-time availability of your company’s top 100 products. Perhaps the results can’t be cached, or can only be cached for a short time because it’s supposed to be “real-time” data. But maybe the process of calculating what those top 100 products are takes much longer and that step can be cached. Now your real-time call only has to check availability on a pre-calculated list of products.
Two exceptions:
If the list is really short then the difference may be trivial.
Also, if you’re supporting a multilingual application then the sort order may depend on the user’s language. The order of letters varies by alphabet. In that scenario you might need to sort the list anyway according a given request culture.