Ext JS 4.1 Performance

Source: Internet
Author: User

Original article: http://www.sencha.com/blog/ext-js-4-1-performance/
 

This article describes several factors that affect the performance of Ext JS applications.

  • Network latency seriously affects the initialization Start time, especially the loading time of the Store.
  • CSS processing.
  • Javascript execution.
  • DOM operation.
Network latency

To minimize the application startup time, note that any domain has a limit on the number of concurrent connections to the browser.


This means that if many files are requested from a domain, once the upper limit is reached, subsequent downloads will be queued and will be processed only when a connection slot is released. New browsers have a high range, but it is important to optimize old and slow browsers.


The solution is to use the Sencha SDK tool to generate a single series of script files required by the application.


For more information, see Ext JS 4.0.

 

The "create" command of the SDK analyzes the applications loaded to the page and loads all files referenced by the requires and user attributes in the class definition, then, create a script file that contains all the required class definitions in the correct order.


You can view detailed information about the Sencha System in Ext JS 4.1.

 

Another way to reduce network latency is to enable GZIP compression for Ext JS pages and their related scripts and style files on the Web server.

CSS Processing

CSS selection matches the parent node pointer of DOM from right to left.

This means that the following style processing process is: Find the matched span in the document, and then search for the ancestor nodes that match the two specified style class names along the parent node axis.

 
 
  1. .HeaderContainer .nav span 

Therefore, using a single element makes it more efficient to determine the style of the class name.

 

Javascript Execution
 

The following points must be kept in mind when optimizing Javascript code:

  • Avoid using the old or bad Javascript Engine.
  • Optimize frequently-repeated code.
  • Optimize the code executed during rendering or layout
  • It is best not to execute any additional code during initialization rendering or layout.
  • Move the unchanged expression out of the loop.
  • Use the for loop instead of Ext. Array. each.
  • If the code in the condition in the function is often called, if necessary, move the condition outside the function, refer to the call to fireEvent by Ext JS code library ).
  • Installing and disassembling the call framework in a poor Javascript engine makes the device required for function calling very slow.
Code optimization example

Imagine that a statistical application provides some operations for the data column of the Grid, and adds menu items to the Column Title menu of the Grid to perform the required operations on any call column.


The handler must obtain the relevant context information and the column title of the current activity to be operated:
 

650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/130I55546-0.png "/>

The GitHub example demonstrates two ways to perform this operation. It can run in the SDK sample directory of any version.

The first method used to aggregate the active columns is as follows:

 
 
  1. function badTotalFn(menuItem) {  
  2.    var r = store.getRange(),  
  3.        total = 0;  
  4.    
  5.    Ext.Array.each(r, function(rec) {  
  6.        total += rec.get(menuItem.up('dataIndex').dataIndex);  
  7.    });  

Here are several error practices. First, use Ext. each to call the transfer function for each record in the array. As you can see, function settings affect performance. Secondly, the results of the menuItem. up ('dataindex') expression remain unchanged. It only needs to be executed once and can be placed outside the loop.
 

 

Therefore, you can optimize the code into the following code:

 
 
  1. function goodTotalFn(menuItem) {  
  2.     var r = store.getRange(),  
  3.         field = menuItem.up('dataIndex').dataIndex;  
  4.         total = 0;  
  5.    
  6.     for (var j = 0, l = r.length; j < l; j++) {  
  7.         total += r[j].get(field);  
  8.     }  
  9.  } 

This may seem insignificant, but the performance difference is significant.

 

In the following table, the computing function provides a measurable time after 10000 iterations:

Browser Bad Good
Chrome 1700 ms 10 ms
IE9 18000 ms 500 ms
IE6 Gave up 532 ms


As we can see, even if there is no iteration, IE9 takes 1.8 seconds to process the operation in the first method.

Use a page analyzer to measure performance

The page analyzer is an example of the SDK, which can be found in the example/page-analyzer directory. It runs pages of the same domain in the capture framework, and then captures Ext JS examples to analyze the layout performance and the performance of any method of any object.

If Chrome is used, you need to use the "-enable-benchmarking" command on its command line to enable the microsecond timing accuracy.

To analyze the performance of the key locations in the preceding example, switch to the "performance" tag, select the "Accumulators" tag in the tag panel in the lower left corner, and paste the following code to textarea:

 
 
  1. {  
  2.     "Component.up": {  
  3.         "Ext.Component": "up" 
  4.     },  
  5.     "CQ.is": {  
  6.         "Ext.ComponentQuery": "!is" 
  7.     }  

Make sure that the two aggregate computing functions are iterated for 10000 times to obtain accurate performance.

 

Then, load the Grid performance test example in the page analyzer, use "Get total in bad way" to start the total, and click "UPdate Stats" in the upper right corner of the page analyzer ".

650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/130I55311-1.png "/>

Then, click "Reset" to clear the accumulators, add the "Build" timer, use "Get total in good way" to aggregate, and click the "Update Stats" button of the page analyzer.

In the "Grid" subtab of the "performance" tab, the following two running results are displayed:

 

650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/130I51931-2.png "/>

As you can see, the number of times that the unchanged form method calls the ComponentQuery method outside the loop is much less.

Merge multiple la s

Ext JS 4 will automatically layout based on content changes or size changes. This means that when the text of a button changes, it will lead to the re-layout of its toolbar because the height of the button may change ), the height of the Toolbar may change ).

For this reason, it is very important to merge multiple layout operations when the content or size changes. You can use the following code to achieve this:

 
 
  1. {  
  2.     Ext.suspendLayouts();  
  3.     // batch of updates  
  4.     Ext.resumeLayouts(true);  

If the parameter is set to true, the layout is re-enabled. When it runs to this point, any queued layout requests are cleared.
 

 

Reduce DOM burden

It is important to reduce the number of nested containers or components to achieve as few layers as possible, which can avoid repeated layout operations and DOM backflow because these overhead are expensive.

Another principle to be followed is to use the simplest container or layout for necessary work.

A common example is to nest a component when placing a Grid in a TabPanel. The following is a common method:

 
 
  1. {  
  2.     xtype: "tabpanel",  
  3.     items: [{  
  4.         title: "Results",  
  5.         items: {  
  6.             xtype: "grid" 
  7.             ...  
  8.         }  
  9.     }]  

I don't know why I want to add a common panel as a sub-entry of the label panel, and then place the Grid in the Panel. Such a nested layer is useless.

 

In fact, this damages the operation of the label panel, because the layout of the encapsulated panel is not configured, so the size of its sub-component Grid cannot be changed, this means that it cannot adapt the label panel size and Scroll Based on the label panel height.

The correct statement is as follows:

 
 
  1. {  
  2.     xtype:”tabpanel“,  
  3.     items: [{  
  4.         title: ”Results“,  
  5.         xtype: ”grid“,  
  6.         ...  
  7.     }]  
Why is this principle important?

Keep the component tree or DOM tree as lightweight as possible. The main reason is that in Ext JS 4, many components are containers with sub-components and have their own layout manager. For example, the panel title is now a container class, you can configure other components in addition to the title text and tool buttons.

Although titles as hierarchical containers bring additional overhead, they make the uidesign more flexible.
 

In addition, in Ext JS 4, components use the component layout manager to manage the size and position of the internal DOM structure, rather than using the onResize method as in Ext JS 3. x.

Visualized component tree

When we follow the above principles to design the UI, we can think of the UI as a tree structure. For example, a Viewport can be imagined:

 

650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/130I55S0-3.png "/>

To render the yield Component tree, it operates twice.

The first time, The beforeRender of each component will be called, and then the getRenderTree will be called to generate the configuration object of DomHelper with HTML tags and add it to the rendering cache.

After the first time, the HTML code representing the entire tree is inserted into the document at one time, which reduces DOM processing when the application structure is created.

The tree then goes over and calls the onRender method of each component to connect the component to their related DOM node. Then, call afterRender to complete rendering.

After that, the complete initial layout is complete.

This is why creating a lightweight UI is very important.

Study the structure of the lower panel:

 
 
  1. Ext.create('Ext.panel.Panel', {  
  2.     width: 400, height: 200,  
  3.     icon: '../shared/icons/fam/book.png',  
  4.     title: 'Test',  
  5.     tools: [{  
  6.         type: 'gear' 
  7.     }, {  
  8.         type: 'pin' 
  9.     }],  
  10.     renderTo: document.body  
  11. }); 

It will lead to a very complex UI structure:
 

 

 

650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/130I52647-4.png "/>

Try to avoid shrinking and encapsulating shrinkwrapping, and adjust the size according to the content)

Although Ext JS 4 provides a container that can automatically resize Based on the content, it is called "shrinkwrapping" in Ext JS), but this will increase the burden on some la S, the second is that the calculation result will cause the browser to flow back, and then the calculated height and width will be used to re-layout.

Avoid DOM refresh size and improve performance.

Avoid limiting the minHeight, maxHeight, minWidth, and maxWidth values as much as possible)

If the limit is hit, the entire layout needs to be re-computed. For example, when a sub-component using the flex-defined box layout receives its calculated width less than the defined minWidth, it will be fixed to the minimum width, and the layout of the entire box will have to be recalculated.

Similarly, when the stretchMax configuration item is used in a box layout, all child components are switched to a fixed vertical size, for example, the Hbox layout height, and the layout is recalculated.

Avoid DOM of post-rendering components

To avoid DOM backflow and re-painting, try to avoid the DOM structure after component rendering. The alternative is to use the provided hooks to modify the component configuration before generating HTML code.

If you really want to modify the ODM structure, rewrite the getRenderTree method as the final method.

Grid Performance

The table size affects performance, especially the number of columns. Therefore, you must keep as few columns as possible.

If the dataset is very large and you do not want to use the paging toolbar in the UI, you can use a buffer rendering method commonly known as "infinite Grid.

To achieve this, you only need to add the following configuration items to the Store:

 
 
  1. buffered: true,  
  2. pageSize: 50, // Whatever works best given your network/DB latency  
  3. autoLoad: true 

Then load and maintain it as usual.

 

How it works

Grid calculates the rendering table size and monitors the scroll position based on the configuration items of the PagingScroller object. The following configuration items need to be configured during rolling:

  • TrailingBufferZone: Number of rendered records that are kept in the visible area.
  • LeadingBufferZone: number of records rendered in the visible area.
  • NumFromEdge: the boundary value between the scrolling and visible area of the table before the table is refreshed.

The rendered table must contain enough rows to fill the height of the view, plus the buffer period, the size of the leading buffer, and numFromEdge * 2) to create a scroll overflow.

When the scrolling result of the table is monitored and the number of rows between the end of the table and the view is smaller than numFromEdge, use the next piece of data in the dataset to re-render the table and locate it, so that the visible position of the row remains unchanged.

In the best case, re-rendering the required rows is already in the page cache, and the operations are instantaneous and imperceptible.

To configure these values, you can configure them in the verticalScroller configuration item of the Grid:

 
 
  1. {  
  2.     xtype: 'gridpanel',  
  3.     verticalScroller: {  
  4.         numFromEdge: 5,  
  5.         trailingBufferZone: 10,  
  6.         leadingBufferZone: 20  
  7.     }  

This means that 40 rows of overflow data are provided to the visible area of the Grid for smooth scrolling, and re-rendering will occur in less than 5 rows between the table boundary and the visible area.

 

Keep the MPs queue complete

It is a Store job to keep the page cache and prepare data for future scrolling. Store also has trailingBufferZone and leadingBufferZone.

When a table Request re-renders a row, after the request row is returned, Store will ensure that the cached data covers the data required for the two regions. If the data is not cached, it will request data to the server.

Both regions have relatively large default values. developers can reduce or increase the number of pages they keep in the pipeline.

Cache failed

When the data set is not cached, loading masking and delayed rendering are displayed because the data needs to be requested from the server. However, this situation has been optimized.

The page range that contains the data required for the display area will give priority to requests. When the data arrives, it will be re-rendered immediately. The data required by trailingBufferZone and leadingBufferZone will be sent immediately after the data required by the UI is loaded.


 

Cache trimming

By default, the cache calculates the maximum size. In addition, it also discards recently used pages. The page size is the leadingBufferZone of the scroll bar plus the visible area size, plus the trailingBufferZone and Store purgePageCount configuration items. Adding purgePageCount means that once a page is accessed, it can be returned quickly, rather than sending a request to the server.

If the purgePageCount value is 0, it means that the cache can continue to grow without trimming, and may eventually grow to include the entire dataset. This is a very useful option when the dataset is not too big. Remember, humans cannot understand too much data, so displaying more than thousands of rows of data in the Grid is actually not very useful, which may mean they use the wrong filtering conditions and need to re-query.

Place the entire dataset on the client

If the dataset is not an astronomical dataset, it is feasible to cache the entire dataset on the page.

You can test the feasibility by using the "Infinite grid Tuner" example in examples/Grid/infinite-scroll-grid-tuner.html under the SDK sample directory.

If you set the leadingBufferZone of the Store to 50000 and set purgePageCount to 0, this will produce the expected results.

The leadingBufferZone will allow the Store to maintain the integrity of the pipeline, which means that the 50000 discount is very complete.

PurgePageCount0 means there is no limit on the growth of the number of pages.

Therefore, when you click "Reload", the data page required by the visible area will be requested first and then rendered.

Then, the Store will try to fill up a huge leadingBufferZone. Soon, the entire dataset is cached, and data access anywhere in the scrolling area is real-time.


 

Author:Nige "Animal" White
Nigel brings more than 20 years experience to his role as a software Defined ect at Sencha. he has been working with rich Internet applications, and dynamic browser updating techniques since before the term "Ajax" was coined. since the germination of Ext JS he has contributed code, documentation, and design input.

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.