12 steps to creating a high-performance web APP

Source: Internet
Author: User

Today, Web apps increasingly focus on the user's interaction experience, and understanding how performance is optimized can effectively improve the user experience. Read and practice the performance optimization techniques below to help you improve your application's fluency, rendering time, and other aspects of performance.

Overview

Performance optimization for Web apps is a tedious task, not only because building a web app requires a front-and-back collaboration, but also requires a multi-faceted technology stack: databases, backend, and frontend, which need to run on multiple platforms: IOS, Android, Chrome,firefox,edge. It's too complicated! However, there are a number of practical and common ways to optimize the performance of your Web App. In the next section, we'll step through the details.

A study from Bing shows that every time the page load is increased 10ms , revenue is reduced every year $250k . ———— Rob Trace and David Walp, senior product Manager from Microsoft

Premature optimization

The challenge of performance optimization is to identify areas of development that deserve optimization. Donald Knuth said a classic: "Premature optimization is the root of all evil." The implication behind this sentence is that the performance of spending a lot of time improving is 1% meaningless. At the same time, some optimization schemes affect readability or maintainability, and even introduce new problems. In other words, performance optimization should not be seen as a "way to squeeze application performance", but rather as "an exploration of the balance of performance and benefits." When practicing the following optimization techniques, it is important to keep in mind that blind optimization can affect productivity and even outweigh the gains. The best way to do this is to use analysis tools to find performance bottlenecks and maintain a balance between performance optimization and development efficiency, maintainability, and more.

Developers waste a lot of time thinking about or worrying about the execution of the program, but in fact, from the point of view of debugging and post-maintenance, these optimizations often have a serious negative impact. We should focus on the operational performance of 97%: Premature performance optimization is the root of all evils. Of course, we should not give up the pain point of 3%. ———— Donald Knuth

File compression and Module packaging

JavaScript is usually distributed directly using the source code, and the source code is often parsed slower than the bytecode. For small scripts, both parsing is not very fast, but for large applications, it can significantly affect the startup speed of the application. Addressing this pain point is one of the starting points of WebAssembly, which will significantly improve the program's start-up speed. File compression is the process of rejecting useless characters in a file, although the processed code loses readability, but improves the browser's parsing speed.

On the other hand, module packaging can combine different scripts into one script, reducing HTTP requests and reducing resource load times. Usually, this kind of work will be given to the appropriate tools to deal with, such as Webpack.

function insert(i) { document.write("Sample " + i);}for(var i = 0; i < 30; ++i) { insert(i);}

After compression:

!Function (r) {function T(o) {if (E[o])return e[o].exports;var n=e[o]={exports:{},id:o,loaded:!1};Return R[o].call (n.exports,n,n.exports,t), n.loaded=!0,n.exports}var e={};return t.m=r,t.c=e,t.p=0)} ([function (r,t) { Span class= "function" >function  e (R) { document.write ( "Sample" +r)} for (var o= 0; 30>o;++o) e (o)}]); //# sourcemappingurl=bundle.min.js.map       
Deep packaging

Using Webpack, we can also compress CSS and merge images to further improve the program's startup speed. For more information about Webpack, please refer to the official documentation.

Load on Demand

Loading resources on demand or lazy loading of resources (especially pictures) is a great help in optimizing the performance of your Web App. For pages with more pictures, lazy loading usually has the following three benefits:

    • Reduce concurrent requests, relieve server pressure, and increase loading speed
    • Reduce browser memory usage
    • Reduce the load on the server

Pictures or other resources lazy loading scenarios typically load the first screen resource when the program starts, and continuously load the resources that are about to enter the viewport as the page scrolls. Because this approach often needs to be coordinated with the page structure and development approach, it is often possible to use existing plugins and extensions to implement lazy loading. For example, React-lazy-load is a react-based image lazy loading plugin:

Const MyComponent = () = (<Div>Scroll to load images.<div classname= "filler"/> < Lazyload height={762} span class= "attribute" >offsetvertical={300}> <img < span class= "attribute" >src= ' http://apod.nasa.gov/apod/image/1502/HDR_ Mvmq20feb2015ouellet1024.jpg '/> </ lazyload> (...)             

A typical on-demand loading example is Google's image search tool, click on the link and scroll through the page, open the Developer tool to note the load time of the resource.

Array-ids

If you are using React , Ember , Angular, or other third-party libraries that manipulate the DOM, then using Array-ids (or features in Angular 1.x track-by ) can have Improve the performance of the page, the performance of dynamic site optimization is particularly prominent. From the latest benchmarks we can also see the advantages: more benchmarks:virtual DOM vs Angular 1 & 2 vs Mithril.js vs Cito.js vs the Rest (Updated and improved!).

The core concept behind it is to reuse existing nodes as much as possible. Array-ids facilitates the DOM operations engine to match the actual node based on the obtained DOM node. If not array-id track-by , most third-party libraries will simply and brutally delete nodes and then create nodes, which can seriously affect the execution speed of the program.

Cache

The cache is often used to store frequently called data, and when the cached data is called again, the data can be directly supplied by the cache, improving the response speed of the data. Typically, a Web App is made up of multiple components that can discover cached shadows. For example, the cache used between the dynamic content server and the client can improve the response time of the page by reducing the server load by decreasing the general request, such as caching in the code to optimize some common script access patterns. In addition, there are database caches, long process caches, and so on.

In short, caching is an effective way to improve application responsiveness and reduce CPU load. In a development system, the hardest part is not how to use caching, but figuring out where to use it. For this issue, I recommend using the Event Analysis Tool (Profiler): Identify performance bottlenecks, detect the success of the cache, and test whether the cache is prone to failure ... All these problems need to be practiced in order to draw valid conclusions.

Caching can be used to optimize resource loading, for example, by using Basket.js, a script that uses a local storage cache app, to quickly get the appropriate resources from local storage when the resource is called for the second time.

Amazon CloudFront is now a popular cache service. CloudFront works like a content distribution network (CDN), where you can set up caching for dynamic content.

Http/2

At present, there are more and more browsers support HTTP/2. The advantage of HTTP/2 is its concurrent connection to the server, for example, if you need to load small resources (provided you do not package the resources) more, HTTP/2 in response time and performance is far better than HTTP/1. You can click on the Akamai HTTP/2 example to see the difference between the two.

Performance profiling

Profiling is an important step in the performance optimization of your application. As mentioned above, blindly optimizing applications often reduces productivity, creates new pain points, and is difficult to maintain. The role of profiling is to identify potential areas of risk in your application.

Responsiveness is a very important metric for WEB applications, so developers will try to increase the speed of loading and rendering of the page as much as possible. The Chrome Browser offers a range of excellent profiling tools, the most common of which is the timeline and network in the developer tools that make the best Use of them to pinpoint the risk areas for response speed.

Timeline Panel makes it easy to quickly find time-consuming operations.

Network The panel facilitates the positioning of response speed issues caused by request time and serial loading.

In addition, the performance of the application can be effectively improved if memory usage is reasonably analyzed. If your page has a large number of visual elements (such as dynamic tables) or a large number of interactive elements (such as games), then the analysis of memory usage can effectively reduce the lag and increase the frame rate. If you would like to learn more about memory profiling in the Chrome developer tools, please refer to this article: "4 Types of Memory Leaks in JavaScript and" Get Rid of them ".

The Chrome developer tool can also be used to dissect the CPU, for more details please refer to this article from Google Docs: "Profiling JavaScript Performance".

Identify the core pain points of performance to enable you to optimize performance more effectively.

In contrast, performance profiling of the backend is slightly more difficult. In general, it's a good idea to find the appropriate server from the most time-consuming request. There is no recommended performance profiling tool for the backend, because the specific profiling tools depend on the specific backend technology stack.

Algorithm

In most cases, choosing a more efficient algorithm can yield better results than local optimization. In a sense, profiling the CPU and memory can help developers identify the larger performance bottlenecks in the application. If these bottlenecks are not caused by code errors, it is likely that the problem is the algorithm.

Load Balancing

In the caching section above, the concept of a content distribution network (CDN) is briefly mentioned. Distributing the load based on a server or geographic region can effectively increase the responsiveness of resources, which is particularly noticeable when dealing with concurrent links.

In short, load balancing is similar to a polling scheme, built on a reverse proxy server Nginx or a mature distribution network such as Cloudflare and Amazon CloudFront .

In order to achieve load balancing, dynamic content and static content need to be separated to facilitate parallel connection. In other words, serial access weakens the ability of the load balancer to retrieve the best path and distribute it. In addition, loading resources in parallel can speed up application startup.

Load Balancing can also be constructed in a very granular form. If the data model does not maintain a good match with the final consistency algorithm or cache, it will inevitably cause many problems. Fortunately, the data requested by most applications is a reduced set, which itself has a higher level of consistency. If your application does not yet have the ability to do so, then you need to consider refactoring it.

Homogeneous JavaScript

For WEB applications, a way to enhance the user experience is to reduce startup time or to reduce the first screen rendering time, which is especially important for single-page applications that require a large number of logical operations on the client. The more logical operations you perform on the client, the more often it means that more resources need to be loaded before the first screen is rendered. The same javascript is used to solve this problem: JavaScript can be executed both on the client and the server, so it can render the first screen on the server, then send it to the client, and then the client's JavaScript will take over the rest of the logic processing. This scenario limits the server to a JavaScript-only framework, but improves the user experience. At present, This method can be used directly in Meteor.js. In addition, this is also possible in the React framework, as shown in the following code:

var React = require (' React/addons ');var reactapp = React.createfactory (Require (function (app) {App.get (  '/', function (req, res) { span class= "comment" >//react.rendertostring takes your component //and generates the markup var reacthtml = React.rendertostring (Reactapp ({})); //Output html rendered by react  //console.log (myapphtml); Res.render ( ' Index.ejs ', {reactoutput:reacthtml}); });}; 

Here is a simple example of meteor.js:

if (meteor.isclient) {Template.hello.greeting =function () {Return"Welcome to MyApp."; }; Template.hello.events ({' Click Input ':function  () {//template data, if any, was available in ' this ' < span class= "keyword" >if (typeof console!==  ' undefined ') console.log ( "You pressed the button");});} if (meteor.isserver) {meteor.startup (function  () {//code to run on server at startup}),                

If you are developing large and medium-sized complex applications and support homogeneous publishing, you can try this way and the effect is likely to be shocking.

Index

If the database query takes up too much execution time, you should consider optimizing the execution speed of the database. Each database and data model has its own characteristics. Database optimizations come in many directions: the data model, the database type, and other configurations, so it's not easy to optimize. However, we still have some general optimization techniques, such as: Index. Indexes create fast-access data structures based on database data, improving the retrieval speed of specific data. Most databases now support the indexing function,

Before using the index to tune the database, you should study the current application's access patterns, analyze what queries are most commonly used, which keys or fields are frequently queried, and so on.

Compiling tools

The growing complexity of the JavaScript stack has also contributed to the advancement of language itself. Unfortunately, the development of JavaScript is currently restricted to the user's access environment. Although ECMAScript 2015 has made many improvements to JavaScript, developers are not yet able to follow the code of this specification directly. In response to this problem, there are many compiler tools that are often used to convert ECMAScript 2015 code to ECMAScript 5. In addition, module packaging and file compression are added to the compilation process and are ultimately used to generate code on the online version. These tools convert code to a restricted version, which indirectly affects the efficiency of the execution of the final code. Google developer Paul Irish has tested the effects of transcoding on performance and file size, please click on the link for details. Although the impact is minimal in most cases, these differences are still worth noting, as these differences will grow as the complexity of the application increases.

Blocking rendering

The loading of JavaScript and CSS resources blocks the rendering process of the page. With some tips, developers can load JavaScript and CSS resources as quickly as possible, allowing the browser to display the content of the site as quickly as possible.

For CSS, CSS rules that are inherently consistent with the current page media properties have a higher processing priority. The media properties of the page are matched by the media query of the CSS. Media query notifies the browser which CSS script is for which media property. For example, the CSS used for printing has a lower priority relative to the current screen's display of CSS.

You can <link> set properties related to media queries for labels:

< Link rel= "stylesheet" span class= "attribute" >type= "Text/css" media= "only screen and ( max-device-width:480px) "href=  "Mobile-device.css"/>           

The key to JavaScript is the proper use of inline JavaScript (that is, JavaScript in HTML). Inline JavaScript should be as brief as possible and not block blocking of other parts of the page. In other words, inline JavaScript in the HTML document tree blocks parsing of HTML scripts, forcing the parsing engine to continue parsing until the script executes. If there is a large number of such blocking scripts in the HTML tree or the blocking time is too long, the application's user experience will be severely compromised. Inline JavaScript helps prevent the network from getting too many scripts. Inline forms are not recommended for scripts that are used repeatedly, or for larger scripts.

An effective way to prevent JavaScript from blocking HTML parsing is to load tags asynchronously <script> . This approach restricts access to our DOM (unusable document.write ), but allows the browser to parse and render the page without regard to the execution state of the JavaScript. In other words, to get the best boot speed, you should ensure that all non-essential scripts are loaded asynchronously:

<script src="async.js" async></script>
Servce workers and stream

Jake Archibald's latest article presents an interesting solution for improving rendering speed: Combining service workers and stream for page rendering. The results are quite convincing:

Unfortunately, the API used in this technique is still changing, so it can't be applied to real-world development. The core of this technique is to store a service worker between the website and the client. Service workers can be used to cache data (such as infrequently changing portions of the site's head) to prevent network lookups from failing. If the cache data is lost, it can be quickly obtained via stream.

Extended Reading

For more information and tools on performance optimization, please refer to the following links:

    • Best practices to speeding up Your Website-yahoo Developer Network
    • Yslow-a tool that checks for Yahoo ' s recommended optimizations
    • Pagespeed Insights-google Developers
    • Pagespeed Tools-google Developers
    • HTTP/2: The long-awaited Sequel
Conclusion

As applications become larger and more complex, the role of performance optimization in WEB development is becoming increasingly important. Targeted performance optimization is critical to help reduce time and maintenance costs. With the development of WEB applications, the role is no longer a single content display, learning the general performance Optimization model, you can convert a difficult to use the application of a simple tool. No rule is absolute, only the deep logic of the technology stack is researched and analyzed, and the performance optimization can be done rationally.

12 steps to creating a high-performance web APP

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.