I finally have an understanding of how the NodeVisitor works.
As more and more in Core switches to render arrays within templates, the need for performance improvements increases again.
Fortunately I have found a great solution for a syntax that is really fast and sane at the same time:
{{ attribute(name.foo, attribute(name.foo, "key")) }}
becomes
<?php
if (isset($context["name"])) { $_name_ = $context["name"]; } else { $_name_ = null; }
echo twig_render($context, array( "#twig_reference"=> TRUE, "template"=> $this, "path"=> array(array("name", "name"), array( "attribute", "foo"), array( "attribute", $this->getAttribute($this->getAttribute($_name_, "foo"), "key")))));
?>
As twig_render already needs to check for instanceof TwigReference it can as well also check an arbitrary array key, but instead of getting the reference directly the context is unwrapped by following the stored path.
We also know that render arrays are likely to occur, such we check for array first and only in the case that it is no array, the normal getAttribute function is called.
Note how the code makes proper use of the property that we don't need attribute keys to return references. These use the normal Twig getAttribute function.
Note: It is important to keep getAttribute as much as possible as those are replaced by fast calls to the C extension - if it is installed.
All the new magic is at compile time and while there is still work needed to make it into a proper patch and benchmark it, I'll post some draft (non-patch) here soon.