fabpot/Twig — pull request #543 by VladimirTechMan (2011-12-01 19:52:06+00:00)
Title: Allow using multi-value echoes for adjacent text and expression result printouts in compiled templates

It is quite common, for a good fraction of the templates in use, to contain simple sequences of adjacent blocks of text (most often, some HTML code) and expression result printouts. When compiling those templates, Twig translates those original sequences directly into sequences of 'echo' statements where each text block or expression result is printed out with a separate 'echo' statement.

At the same time, PHP allows the embedded language construct of 'echo' to have multiple "arguments" separated by commas (not "dots"). In that case all the arguments (PHP expressions) get evaluated and printed out in the sequence given. Compared to printing the same chain of values by separate 'echos' (one per value), a multi-value 'echo' is executed a little bit faster by PHP -- the more values are "bundled" into a single 'echo', the quicker.

If a multi-value echo is executed just on rare occasions, the resulting speedup is hardly noticeable (thus unimportant). But it starts paying off when calling the same code for hundreds and thousands page requests per sec, which is where Twig tries to be (and is) one of the best template frameworks in its class.

With all that in mind, I would like proposing a few code changes -- quite simple and moderate in size -- to allow combining adjacent printouts of text blocks and expressions into multi-value echoes in the templates compiled by Twig. The related handling is controlled with a new Environment parameter called "multivalue_echoes" that takes a boolean value so that the effect can always be controlled by the Twig users.

Internally the change is implemented with two extra node types (classes) added, Twig_Node_PrintMultiple and Twig_Node_SandboxedPrintMultiple. The appropriate changes have been done in Twig_Environment, Twig_Parser, and Twig_NodeVisitor_Sandbox. See the deltas for details.

The changes are fully compatible with the optimizations done by Twig, including the newly added OPTIMIZE_VAR_ACCESS.

I would like to welcome Fabien as well as other Twig developers and users to look at this proposal, assess it themselves (the code changes done and the results) and (hopefully) consider making it a part of a future release of Twig.

If this proposed addition to Twig will eventually be of interest and of help to others, I will be glad.