Friday, March 1, 2013

Why Python, Ruby, and JavaScript are slow

Jinja2, which can be used in lieu of Django's templating engine, recommends in its documentation to use the markupsafe library:

More Speed with MarkupSafe

As of version 2.5.1 Jinja2 will check for an installed MarkupSafe module. If it can find it, it will use the Markup class of that module instead of the one that comes with Jinja2. MarkupSafe replaces the older speedups module that came with Jinja2 and has the advantage that is has a better setup script and will automatically attempt to install the C version and nicely fall back to a pure Python implementation if that is not possible.

The C implementation of MarkupSafe is much faster and recommended when using Jinja2 with autoescaping.
>>> import markupsafe
>>> markupsafe

If we don't use the markupsafe package, Jinja has to rely on a Python implementation, which basically means for each character it encounters, it needs to expand the buffer by the extra # of characters, move the data, and repeat the process all over again. The C library extension seems to try to be smarter by using BYOB (bring your own buffer) by expanding the buffer to the total size and block copying the data when escaping is not needed.

This deck helps to sum up why the C implementation is much faster:

No comments:

Post a Comment