Here are 10 performance rules that we follow when using node.js:
1. Avoid using sync code
In the design, the node.js is a single thread. To allow a single thread to handle many concurrent requests, you can never allow a thread to wait for blocking, synchronizing, or long-running operations. A notable feature of Node.js is that it is designed and implemented from top to bottom to achieve asynchrony. This makes it ideal for event-type programs.
Unfortunately, there is still a possibility that a synchronous/blocking call might occur. For example, many file system operations have simultaneous and asynchronous versions, such as WriteFile and Writefilesync. Even if you use code to control the synchronization method, it is possible to use the external function library of the blocking call unnoticed. When you do this, the effect on performance is enormous.
Good:write Files asynchronously
fs.writefile (' message.txt ', ' Hello Node ', function (err) {
Console.log (" It ' s saved and the server remains responsive! ');
Bad:write files synchronously
fs.writefilesync (' message.txt ', ' Hello Node ');
Console.log ("It ' s saved, but you just blocked all requests!");
Our initialization log unintentionally contains a synchronization to write the content to disk when it is implemented. If we don't do performance testing then it's easy to overlook the problem. When a Node.js instance in developer box is used as a standard test, this synchronous call will cause performance to be reduced from thousands of requests per second to only dozens of.
2. Close Socket Pool
Node.js HTTP clients automatically use socket pooling: By default, it restricts each host to only 5 sockets. While the reuse of sockets may make the increase in resources under control, it can lead to a series of bottlenecks if you need to process many of the data from concurrent requests from the same host. In this case, it is a good idea to increase the value of the maxsockets or to turn off the socket pool:
Disable Socket Pooling
var http = require (' http ');
var options = {...};
Options.agent = false;
var req = http.request (options)
3. Do not allow static resources to use Node.js
For static resources such as CSS and pictures, use standard webserver instead of node.js. For example, a nginx is used for LinkedIn movement. We also use the Content Delivery network (CDNS), which can copy static capital from the world to the server. There are two benefits: (1) Reducing the load on our Node.js servers (2) CDNs can allow static content to be passed on servers closer to the user to reduce latency.
4. Render at Client
Let's quickly compare the difference between server rendering and client rendering. If we use Node.js to render on the server side, we will echo HTML pages like the following for each request:
<!--A example of simple webpage rendered entirely server side--> <!
DOCTYPE html>
Notice all the content on this page, except for the user's name, and the rest is static: For each user and page overload content is the same. It is therefore more efficient to have node.js return only the dynamic content required by the page in JSON form.
{' name ': ' John '}
The rest of the page-all static HTML tags-can be placed in JavaScript templates (such as underscore.js templates):
<!--An example of a JavaScript template, can be rendered client side-->
<! DOCTYPE html>
Performance improvements come from these places: as the 3rd says, static JavaScript templates can be provided on the server side via webserver (such as Nginx), or with better CDN implementations. In addition, JavaScript templates can be slow to exist in the browser or stored locally, after all the initial page load, the only data that needs to be sent to the client is JSON, which will be the most effective. This method can greatly reduce the amount of cpu,io, and node.js load.
5. Use gzip
Many servers and clients support gzip to compress requests and responses. Whether you are replying to a client or sending a request to a remote server, be sure to use it fully.
6. parallelization
Try to get all of your blocking operations-sending requests to the remote service, DB calls, and file system access parallelization. This will reduce the latency of the slowest blocking operation, rather than the wait time for all blocking operations. To keep the callback and error handling clean, we use step to control traffic.
7.Session liberalization
LinkedIn Mobile uses the Express framework to manage request/response cycles. Many of the express examples include the following configuration:
App.use (Express.session ({secret: "Keyboard Cat"});
By default, session data is stored in memory, which adds huge overhead to the server, especially as users grow. You can use an external session store, such as MongoDB or Redis, but each request will cause a remote call to get the cost of the session data. Where possible, the best option is to store all stateless data on the server side. You'll see better performance with the session being liberalized by not including the express configuration above.
8. Using binary modules
If possible, replace the JavaScript module with a binary module. For example, when we convert from the SHA module written in JavaScript to the compiled version of Node.js, we see a great leap forward in performance:
Use built in or binary modules
var crypto = require (' crypto ');
var hash = Crypto.createhmac ("SHA1", key). Update (Signaturebase). Digest ("base64");
9. Replace the client library with standard V8 JavaScript
Many JavaScript libraries are created to be used in a Web browser because the JavaScript environment is not the same: for example, some browsers support functions such as foreach,map and reduce, but some browsers do not support them. Therefore, client libraries often use a number of inefficient code to overcome browser differences. On the other hand, in Node.js, you know exactly which JavaScript methods are valid: V8 JavaScript engine support Node.js implementation ECMA-262 the ECMAScript specified in version fifth. By using the standard V8 JavaScript function instead of the client library, you will find that performance is significantly improved.
10. Keep your code small and light
Using mobile devices makes access slow and high latency, which tells us to keep our code small and light. The same idea is maintained for server code. Occasionally look back at your decision and ask yourself questions like, "Do we really need this module?" "Why do we use this framework, and is it overhead worth our use?" "Can we implement it in a simple way?" ”。 Small and lightweight code is often more efficient and fast.
Try
We work very hard to make our mobile apps fast. Try on the iphone apps, Android apps and HTML5 Mobile versions of these platforms to let us know how we are doing.