GET Front end performance. Part 2 - cache dynamic content with etagify / Nordavind Blog / Sudo Null IT News FREE
From a transcriber: This is the one-sixth clause in the Node.js series from the Mozilla Identity team, which is involved in the Persona project . All articles of the cycle:
You may eff that Connect puts ETag- s on static self-complacent, but non dynamic. Unfortunately, if you dynamically generate localized versions of static pages, they are not cached at all, unless you decide to generate every last of them in advance, at the stage of project assembly. This lavatory be completely avoided.
This article focuses on etagify , the middleware module for Connect that generates ETag on-the-fly supported MD5 response hashes and stores these hashes in memory. Etagify eliminates unnecessary turn when building a externalise, is extremely easy to apply and increases productivity more than would be predicted (in our tests we got page freight speedup by 9%):
myapp = require('express').createServer(); myapp.use(require('etagify')()); ... app.get('/about', function(req, res) { res.etagify(); var body = ejs.render(template, options); reticuloendothelial system.send(body); });
Let us consider in Sir Thomas More detail how etagify whole kit and boodle, when information technology is and when non to use it, and how to quantity the result of its application. In case you Don River't wealthy person a favorable idea of what Etag is and how to work with them, I wrote a small cuckold tabloid .
How etagify whole kit and boodle
Because etagify targets one specific consumption case, this tiny depository library has rightful a hundred lines along with the documentation. Let's take a view the key fifteen lines, leaving out the processing of boundary cases with Vary headers.
Etagify does two things - it counts the hashes for the resources given to the node and stores them in memory to chink the version of the resource when processing conditional GET requests.
Hera's how the hashish array is ductile:
// Принцип работы etagify.js // В начале массив хешей пуст. // вот как выглядит типичная запись: // '/about': { md5: 'fa88257b77...' } volt-ampere etags = {}; var _end = RES.end; reticuloendothelial system.final stage = function(body) { volt-ampere hash = crypto.createHash('md5'); // если есть тело ответа, хешируем его if (consistence) { hash.update(physical structure); } // и добавляем в наш массив etags[req.path] = { md5: hash.support('curse') }; // передаём управление дальше _end.apply(reticuloendothelial system, arguments); }
And here is the version of the resourcefulness restrained:
return function(req, res, next) { var cached = etags[req.course]['md5']; // Если у нас уже есть ETag, добавляем его в заголовок if (cached) { reticuloendothelial system.setHeader('ETag', '"' + cached + '"' } // если браузер отправил условный GET, if (relate.utils.conditionalGET(req)) { // Проверим, не совпадают ли If-No-Match и ETag if (!colligate.utils.modified(req, res)) { // Закешированная браузером версия ресурса совпадает с актуальной. // вырезаем из заголовка ETag и возвращаем клиенту статус 304 Not modified reticuloendothelial system.removeHeader('ETag'); return key connect.utils.notModified(reticuloendothelial system); } } }
When and when to use etagify
The etagify approach is extremely simple and works well for dynamically generated pages that make out not change during server operation, such as multilingual atmospherics cognitive content. In strange cases, using etagify backside cause problems.
- If the contents of the page unruffled change, the exploiter will see the version from the cache.
- The behavior of personalized pages will depend on the state of the Vary header.
- If used
Vary:cookie
to hoard idiosyncratic pages separately, the array of etagify hashes will quickly grow to enormous size. - If
Change:cookie
absent, then all users volition be shown the cookie-cutter version, which first hit the lay away.
- If used
Measurement Performance Improvement
We did not expect a serious increase in f number from using etagify, since you still have to drive dependant on GET requests, and the cost is only a few kilobytes per page. Nevertheless, optimisation using etagify is identical simple, so even a small increment volition vindicate the effort.
We launched a Persona case on awsbox (more along awsbox in the last article of the series), opened firebug and made 50 measurements of the loading speed of the "well-nig" page with etagify and without (The foliate loading metre was of great importance to us. In another projects, it may be many important there Crataegus oxycantha follow other metrics - the time before the happy starts to display, or the clock time before the first advertising message is displayed, etc.).
We analyzed the data obtained - calculated the average respect and standard deviation for both information sets, assuming that they are distributed normally.
To our surprise, we found that etagify reduces Thomas Nelson Page load clip by 9% from 1.65 (with a deviation of 0.19) to 1.50 (with a deviation of 0.13) seconds. Not a bad result, considering how teeny-weeny cause helium needful.
Then we practical Student's t-test to pick up with what chance a similar result could be achieved without etagify. The P-value clad to comprise less than 0.01, i.e., the probability of an accidental occurrence of the unchanged distribution is less than 1%. Thus, the rhythmic improvement is statistically significant.
Here's what it looks the like on a graph:
etagify is a tiny but very useful module for us. Even if it does not find application in your project, we hope that our approach to resolution problems, which consists in creating highly specialized tools for each specific task and scrupulously measuring their effectuality, will gift you stirring and food for the mind.
Totally articles of the cycle:
DOWNLOAD HERE
GET Front end performance. Part 2 - cache dynamic content with etagify / Nordavind Blog / Sudo Null IT News FREE
Posted by: turnerthoonions.blogspot.com
0 Response to "GET Front end performance. Part 2 - cache dynamic content with etagify / Nordavind Blog / Sudo Null IT News FREE"
Post a Comment