What makes Node.js faster than PHP?

Home Forums Programming What makes Node.js faster than PHP?

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #10868
    Sir Boat
    Elvis Acquah

    One key difference between JavaScript and PHP allows Node.js to execute faster than PHP. It has nothing to do with the parser, nothing to do with the dynamics of the language itself… it all boils down to JavaScript’s Event Loop.

    This quirk of the language evolved from JavaScript sharing a thread with the browser window; if JavaScript sat around for several seconds waiting for an AJAX call to resolve, having the browser lock up is a terrible user-experience. JavaScript’s event loop allows programmers to say “Do this thing, then execute this function. In the mean time, I’m going to do X, Y and Z.” PHP has no such feature.

    Node.js takes advantage of this behavior. If you connect to a database in Node.js, you can do other things until you get a response. If you connect to a database in PHP, processing stops until the database responds.

    If used properly, this can provide a significant performance boost to Node.js over PHP. Of course, PHP does technically support threading if you use the pthreads library… and Node.js does technically support threading if you use a variety of plugins or extensions. However, in the normal use-case (without add-ons) Node.js can run faster than PHP.

    To a lesser extent, this can also be due to the way that a Node.js server runs versus the way that a PHP server runs. A PHP server will generally wipe state between requests because each request starts fresh—launched from NGINX, Apache, PHP-FPM, etc. Node.js, on the other hand, runs non-stop as its own standalone process. This means that Node.js doesn’t have to negotiate database connections between every request, and that will give Node.js a slight speed boost over PHP as well.

    There are tools that you can use in PHP to mitigate this problem, too, but they are external tools you have to hook into your process. This is an out-of-the-box feature for Node.js.

    To summarize:

    JavaScript can do other things while it waits for input/output events to resolve, but PHP can’t.
    JavaScript can keep connections open between requests, but PHP can’t.

    When you combine these things, you have a recipe for Node.js being (potentially) faster than PHP.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.