fastify / point-of-view

Template rendering plugin for Fastify
MIT License
344 stars 87 forks source link

perf: setup nunjucks environment on load rather than per request #305

Closed gunjam closed 2 years ago

gunjam commented 2 years ago

Hi,

I've just started playing around with fastify & nunjucks as I'd like to use it for a project, but noticed the performance seemed slow. Had a poke around and point-of-view is setting up the nunjucks environment on each request, which is expensive, so I've made a change to set it up on load.

Here are some before and after autocannon numbers for a simple fastify-cli generated project, rendering a basic nunjucks view:

npx autocannon -c 100 -d 10 -p 10 http://localhost:3000/hello

Before

┌─────────┬────────┬─────────┬─────────┬─────────┬────────────┬────────────┬─────────┐
│ Stat    │ 2.5%   │ 50%     │ 97.5%   │ 99%     │ Avg        │ Stdev      │ Max     │
├─────────┼────────┼─────────┼─────────┼─────────┼────────────┼────────────┼─────────┤
│ Latency │ 560 ms │ 4442 ms │ 7532 ms │ 7635 ms │ 4098.81 ms │ 1979.55 ms │ 7684 ms │
└─────────┴────────┴─────────┴─────────┴─────────┴────────────┴────────────┴─────────┘
┌───────────┬────────┬────────┬────────┬─────────┬────────┬────────┬────────┐
│ Stat      │ 1%     │ 2.5%   │ 50%    │ 97.5%   │ Avg    │ Stdev  │ Min    │
├───────────┼────────┼────────┼────────┼─────────┼────────┼────────┼────────┤
│ Req/Sec   │ 90     │ 90     │ 140    │ 180     │ 135    │ 24.24  │ 90     │
├───────────┼────────┼────────┼────────┼─────────┼────────┼────────┼────────┤
│ Bytes/Sec │ 604 kB │ 604 kB │ 940 kB │ 1.21 MB │ 906 kB │ 163 kB │ 604 kB │
└───────────┴────────┴────────┴────────┴─────────┴────────┴────────┴────────┘
3k requests in 10.1s, 9.06 MB read
171 errors (150 timeouts)

After

┌─────────┬────────┬────────┬────────┬─────────┬───────────┬───────────┬─────────┐
│ Stat    │ 2.5%   │ 50%    │ 97.5%  │ 99%     │ Avg       │ Stdev     │ Max     │
├─────────┼────────┼────────┼────────┼─────────┼───────────┼───────────┼─────────┤
│ Latency │ 186 ms │ 287 ms │ 634 ms │ 1091 ms │ 337.51 ms │ 145.01 ms │ 1248 ms │
└─────────┴────────┴────────┴────────┴─────────┴───────────┴───────────┴─────────┘
┌───────────┬─────────┬─────────┬─────────┬───────┬─────────┬─────────┬─────────┐
│ Stat      │ 1%      │ 2.5%    │ 50%     │ 97.5% │ Avg     │ Stdev   │ Min     │
├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼─────────┼─────────┤
│ Req/Sec   │ 1260    │ 1260    │ 2491    │ 4323  │ 2916.3  │ 955.13  │ 1260    │
├───────────┼─────────┼─────────┼─────────┼───────┼─────────┼─────────┼─────────┤
│ Bytes/Sec │ 8.46 MB │ 8.46 MB │ 16.7 MB │ 29 MB │ 19.6 MB │ 6.41 MB │ 8.45 MB │
└───────────┴─────────┴─────────┴─────────┴───────┴─────────┴─────────┴─────────┘
30k requests in 10.06s, 196 MB read

Checklist