The world's fastest JS template engine

Source: Internet
Author: User

Don't say much nonsense, first on the test:

Pro-Testing please visit: "Online test Address" a single result is not necessarily accurate, please test several times.

TPPL's compiled rendering speed is the famous JQuery author John resig developed by Tmpl! And the second arttemplate also have a one-fold gap.

It seems that every big company chooses to develop its own template engine and open it up, and the result is that the community is flooded with countless engines that are confusing to choose from. As time went on, more and more functions were added, eventually turning a powerful engine into a rusty tractor with a bloated and complicated part. God, I just want to insert a piece of HTML in the Web page, you actually want me to each JS file into 500 lines of code!

No, things should have been easier. Keeping the code simple and efficient also means making life healthier and more enjoyable.

Well, readers who are full of "encapsulation" or "modularity" think differently.

Let's talk about how to make the engine more powerful and efficient.

The template engine is divided into two major camps:

    1. Native syntax
    2. Custom template Syntax

Each of these two schemes has its own good, and the advantage of the former is that it looks and writes more normative and concise, and more "like" is a template. It also works better with compilation, and avoids writing "poor performance" code to the user. Some people think that the custom grammar is more friendly to the page designer, which is a matter of opinion. The disadvantage is that you can usually only customize the simple and limited logical structure of if else and for loops, which is not strong enough and flexible.

The optimization method of custom syntax differs from grammar to syntax, but it is usually turned into a native language logical structure. The main discussion here is the optimization of the native grammar template engine.

For the performance-seeking template engine, there are two obvious directions:

    1. Compiling the result cache
    2. Static compilation results

The cache is well understood and is compiled multiple times at once. Typically, the intermediate value of the string is saved after the initial regular replacement, and is used directly when the rendering is repeated.

Static refers to the compilation of a template string that produces a string-stitched function instead of creating a function every time. The render operation is equivalent to a function call, substituting the variable to complete the string concatenation and return. General engine optimization To this step, the rendering aspect has not much gap and progress of space. Everyone becomes a string concatenation function and can only be optimized at a tiny grammatical level. Here to say, believe that engaged in the front-end development of friends, have "heard" a string splicing "Quick Method": the string fragment push into an array, and finally join return, performance than directly with + or + = string better. Note that this method is out of date! No longer in modern browsers and in node. js. Through the array connection string is just a "temporary solution", along with the major JS compiler optimization and progress, directly using the + string operation, give a compiler in the language to optimize the bottom of the opportunity, we still focus on the future.

When the rendering gap is small, the compilation still has a lot of "moisture" can squeeze out. Of course, part of the template engine integrates advanced features such as file loading, Ajax, and the performance requirements are too high to be reasonable.

The generic native syntax template engine is represented by a string similar to the following:

><%=title%></h1><%For(var iIn content){%> <p> first < %=i% > section: <%=content< Span class= "token punctuation" >[i]%></p ><%}%>      

The compile operation is to convert this string into a function similar to the following:

function(Data){var str="+data. title+";for (var i in data.content) {str += " <p > "+i+" segment: "+data.content[i]+" </p> "  return str;             

The usual situation is to change the string structure, remove the template label, and then create the function using the new function ().

The implementation of the traditional pass parameter is separated by traversing the data object, separating the name value of the object, and then using the object member name as the parameter name of the new function (that is, the variable name), and then passing the function's Appley call to those parameters.

Tmpl uses JavaScript's infrequently used with statement implementations. The implementation is simple, eliminating the keyword var. The Tmpl performance problem is on the with. The With statement provided by JavaScript is intended to be used to more quickly access the properties of an object. Unfortunately, the presence of the WITH statement in the language severely affects the speed of the JavaScript engine because it prevents lexical scope bindings for variable names.

There are many ways to convert, part using split () truncation analysis, part of the use of full regular replacement, more powerful engine using lexical analysis, in short recount.

The full-regular replacement scenario is just a long list of. Replace () chained calls that look like code, but are poorly performing due to intermediate transition states and methods. Lexical analysis Needless to say, a lot of regular slow compilation speed. The focus of the compilation optimization is to minimize the intermediate state and reduce the use of complex regular expressions. After measurement, split () truncation analysis can reduce some of the regular, better performance.

Tppl started with "Template tail label segmentation", namely: Str.split ("%>"), which coincides with the implementation of Tmpl, the above string is divided into 6 paragraphs, and then use a regular replacement for each paragraph:

var tpls = [", " ,"<% for(var i in content){ ", "<p>第<%=i", "段:<%=content[i]", "</p><%}"];

In later performance tests, it was found that this implementation was not significantly improved compared to other engines. It seems to be a further alternative.

After a long time of pondering, finally found that the use of "Template header tag Segmentation" way, can greatly reduce the number of segmentation results, but need to modify the template label:

>[=: Title:]</h1>[:For(var iIn content){:] <p> [= :i:] segment: [=:content[i]: ]</p>[: }:]    /span>                

The square brackets [with the colon: the template label composed of <% can be more clearly distinguish between HTML code and JS logic code. Split the template into 3 segments through. Split ("[:"):

var tpls = [", " for(var i in content){ :]<p>第[=:i:]段:[=:content[i]:]</p>", "}:]"];

As a result, the regular replacement has dropped from 6 to 3 times, with a performance increase of nearly one time! And as the logical structure of the code differs, the performance gains will be greater.

Key Regular Expressions:

var line = "‘"+"<p>第[=:i:]段:[=:content[i]:]</p>".replace(/\[\=\:(.*?)\:\]/g, "‘+$1+‘")+"‘";// ‘<p>第‘+i+‘段:‘+content[i]+‘</p>‘

TPPL source is hosted on Github, address: https://github.com/yangjiePro/tppl

If you have a better method of compiling optimization, welcome to the discussion!

The world's fastest JS template engine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.