1

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?

1
  • 3
    You're presuming that writing something to the console/log is as fast as not doing any operation? Why? Commented Sep 26, 2013 at 21:16

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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.

3 Comments

Are you sure the loop will get skipped? There could be important things going on in the condition and step of the loop. Edit: In fact, the loop does get run. You can see this by timing loops with an empty body but different bounds - a higher limit on i will run for longer.
@AaronDufour Very interesting, thank you for the info. I have thought that V8 will analyze this automatically.
It might be skipped when you run it for the second time - V8 uses statistical profiler to decide what is hot code and where try to optimise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.