Turbocharge Your Mobile App: Caching
Why cache? Well, caching data locally allows content to get to the end user faster. It will reduce the amount of data your app uses (and customers are becoming aware that apps are behind this issue), as well as reduce the battery drain of your application. A simple way to speed up your app, and save customer battery. What are you waiting for?
There are 2 common headers used for caching, and each behaves differently: Cache Control and ETag. I’ll do a quick description of how they work and then conclude with the preferred caching for mobile.
Cache-Control gives the age until the file is expired (in seconds). For example, this file will expire in 1.43M seconds (about 16 weeks). Every time a file is needed, the application looks for the file in the cache first. If the file is there (and is not expired), then it is served immediately (this takes about 250-500ms in my testing). If the file is expired – it is revalidated on the server and either downloaded or served from the cache. If the file is not present in the cache, the file is downloaded from the server. In my test of a 105K file, loading from the cache took under 500ms, and loading from the server took 2-5 seconds. Cache loading in this case is 75-90% faster than download.
ETag: Each file has an unique ETag ID header. When the file is to be served, the application first checks the existing Etag against the server to see if the files are identical. If they are identical, a 304 Not-Modified response is sent. If the file is changed, the new file is downloaded to the device. Note that ETags vary by server, so if you have a distributed server, you should not use them.
In this example, the application has the file in cache, but first uses a HEAD request to just get the Etag header to compare to the cache. Since the request is just for the header, the file is not downloaded (response has zero size on the wire):
This request took about 2 seconds to create the connection, get the request, and then process the image from the cache. Since just reading the file takes 2-5seconds, using an ETag is 0-60% faster than no cache at all.
So which is better?
Since Cache-Control cache retrieval does not need a network connection for validation, it is much faster than using ETags. In the 2 examples above – loading an image from the cache with Cache Control takes under221ms, and 2-3s when using ETags.
Further, Yahoo noted that reducing the number of HTTP requests had the biggest impact on reducing response time. Based on this, they recommend that to reduce latency (For WEB!) removing ETags is a good way to speed your applications. If removing Etags speeds up applications on the web, this speedup will be only accentuated on mobile!
Conclusion: Any caching is better than no caching. However, to take advantage of the speed and power savings that caching can provide, cache control is the preferred method.