Nodejs's 10 performance optimization tips _ node. js

Source: Internet
Author: User
When I was dealing with JavaScript (regardless of the browser or NodeJS), I was always in need of multithreading. In terms of NodeJS, some friends even directly said that NodeJS is single-threaded and cannot make good use of multi-core CPU. During use, we should pay attention to the following 10 performance rules we followed when using Node. js:

1. Avoid using synchronous code

In design, Node. js is single-threaded. To allow a single thread to process many concurrent requests, you can never let the thread wait for blocking, synchronization, or long-running operations. A notable feature of Node. js is that it is designed and implemented from top to bottom to implement Asynchronization. This makes it ideal for event-type programs.

Unfortunately, synchronous/blocking calls may still occur. For example, many file system operations have both synchronous and asynchronous versions, such as writeFile and writeFileSync. Even if you use code to control the synchronization method, you may still need to block the called external function library. When you do this, the performance will be greatly affected.

// Good: write files asynchronouslyfs.writeFile('message.txt', 'Hello Node', function (err) { console.log("It's saved and the server remains responsive!");}); // BAD: write files synchronouslyfs.writeFileSync('message.txt', 'Hello Node');console.log("It's saved, but you just blocked ALL requests!");

Our initialization log does not intentionally include a synchronous call to write the content to the disk. If we do not perform performance tests, it is easy to ignore this issue. When a node. js instance in the developer box is used as the standard test, this synchronous call will reduce the performance from thousands of requests per second to dozens of requests.

2. Disable socket pool

The http client of Node. js automatically uses the socket pool: by default, it limits each host to only five sockets. Although repeated use of sockets may increase the number of resources under control, if you need to process a lot of data from concurrent requests on the same host, it will lead to a series of bottlenecks. In this case, it is a good idea to increase the value of maxSockets or close the socket pool:

// Disable socket pooling var http = require('http');var options = {.....};options.agent = false;var req = http.request(options)

3. Do not use Node. js for static Resources

For static resources such as css and images, use standard WebServer instead of Node. js. For example, LinkedIn mobile uses nginx. We also use the content delivery network (CDNs) to copy static resources around the world to servers. This has two advantages: (1) reducing the load on our node. js server (2) CDNs can transfer static content on servers that are closer to the user to reduce the waiting time.

4. Rendering on the client

Let's quickly compare the differences between server rendering and client rendering. If we use node. js for rendering on the server side, we will return an HTML page like the following for each request:

     LinkedIn Mobile    

Hello John!

Note that all content on this page, except the user name, is static: the reload content for each user and page is the same. Therefore, it is more effective to make Node. js return the dynamic content required by the page in JSON format.

{"Name": "John "}
The rest of the page-all static HTML tags-can be placed in JavaScript templates (such as the underscore. js template ):

     LinkedIn Mobile    

Hello <%= name %>!

The performance improvement comes from these aspects: as mentioned in the third point, static JavaScript templates can be provided on the server side through webserver (such as nginx), or implemented using a better CDN. In addition, JavaScript templates can be cached in a browser or stored locally. After loading all the initial pages, the only data to be sent to the client is JSON, which is the most effective. This method can greatly reduce the workload of CPU, IO, and Node. js.

5. Use gzip

Many servers and clients support gzip to compress requests and responses. Make sure that you fully use the client or send a request to the remote server.

6. parallelization

Try to make all your blocking operations-send requests to remote services, DB calls, and file system access parallelization. This will reduce the waiting time for the slowest blocking operation, rather than the waiting time for all blocking operations. In order to keep the reconciliation and error handling clean, we use Step to control the traffic.

7. Session liberalization

LinkedIn uses the Express framework to manage Request/response cycles. Many examples of express include the following Configuration:

App. use (express. session ({secret: "keyboard cat "}));
By default, session data is stored in the memory, which increases the overhead of the server, especially as the number of users increases. You can use an external session storage, such as MongoDB or Redis. However, each request will result in remote calls to obtain session data overhead. If possible, the best option is to store all the stateless data on the server. If you enable session liberalization by not including the above express configuration, you will see better performance.

8. Use the binary Module

If possible, replace the JavaScript module with a binary module. For example, when we convert the SHA module written in JavaScript to the Node. js compilation version, we will see a great leap in performance:

// Use built in or binary modulesvar crypto = require('crypto');var hash = crypto.createHmac("sha1",key).update(signatureBase).digest("base64");

9. Replacing the client library with standard V8 JavaScript

Many JavaScript libraries are created for use on web browsers because they are different in the JavaScript environment. For example, some browsers support functions such as forEach, map, and reduce, but some Browsers Do Not. Therefore, the client library usually uses a lot of inefficient code to overcome browser differences. On the other hand, in Node. js, you can know exactly which JavaScript methods are effective: the V8 JavaScript Engine supports Node. js to implement the ECMAScript specified in the fifth edition of the ECMA-262. Directly use the standard V8 JavaScript function to replace the client library, and you will find that the performance has been significantly improved.

10. Keep your code small and light

Using a mobile device slows down access and causes high latency, which tells us to keep our code small and light. The same idea is also applied to server code. Occasionally, I look back at your decision and ask myself a question like this: "Do we really need this module ?", "Why do we use this framework? Is the overhead worth using ?", "Can we implement it in a simple way ?". Small and light code is usually more efficient and fast.

Try it

We strive to make our mobile apps faster. Try on IPhone apps, Android apps, and HTML5 mobile platforms to let us know how we are doing.

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.