Should we optimize the code so it loads faster, or should we cache it so that it loads faster? The question really shouldn’t be which one you should do, but in what order you should do it. To properly explain the difference, I’ll have to first clarify what I mean by code optimization and caching.
Code optimization is done by doing away with inefficient, memory, processor, and bandwidth consuming practices. While driving, can make forward 1 block, and make 3 consecutive rights, or 1 left. In this example you’re saving mileage on your car, gas, and time.
Caching is done by storing a copy of the data, and when that data is requested, the copy is used instead of re-generating the files. This applies to server result caching, browser caching, gateway caching, and etc. A non-programming example would be like coca-cola. Originally, it was hand brewed, and eventually the cola was copied, and now its machine brewed. A browser cache grabs the data from the server, copies it into a storage location, and then whenever you request that same file, it’ll access the storage location instead of grabbing it from the server.
Either method reduces a page’s load time. Code optimization will benefit speed when the page is first generated. Caching will benefit the speed any time after the first generation. There really is no reason why we need to choose one or the other, which is why in most cases we do both.
The end result might be the same, but I personally think code optimization should proceed caching. The idea of making messy and inefficiently written code fast by storing it doesn’t sit well with me. Let’s say we have a page that’s taking 20 seconds to load, and we cut it down to 1 second via code optimization. The first time it generates, it’ll take 1 second, and after we cache it, it’ll take even less.
If we do caching first, the first time we generate it, it’ll take 20 seconds, and afterwards, it’ll take a lot less time.
The example might be a bit extreme, but it demonstrates the fact code optimization can go a long way. Obviously in the real-world there are a lot more factors involved that make this decision much harder to make. Ultimately, these decisions will have to be made by those who have a lot a familiar duration of tasks and can effectively perform the cost benefit analysis of the situation, but either way, optimizing code can go a long way.