简体   繁体   中英

Node js performance in request process

Consider this code:

var http = require("http");
http.createServer(function(request, response) {
    for (var i = 0; i < 1000000; i++) {
        console.log("Request received");
    }
    response.writeHead(200, {
        "Content-Type": "text/plain"
    });
    response.write("Hello World");
    response.end();
}).listen(8888, "127.0.0.1");

If we run this code,we should wait for many minute too get response.But if run a for without console.log("Request received"); in a for we get response with high speed? Why?

Simply, one loop in a empty "for" takes nearly null time. But a output with console.log() need a bunch more time and its also synchronous.

First of all starting with v0.6 , console.log() is synchronous (ie. it blocks the main event loop.)

You're writing around 17MBs to stdout on each request. It might take a few minutes for server to respond.

I think because write console.log("Request received"); in console get time process.

console.log is pretty slow like any other print/echo/sysout that does something on your STDOUT console.

EDIT: In addition to that, the interpreter will simply skip the loop if there is no operation in it. If you actually do something in it, it will of course take time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM