Comparing Node.js vs PHP Performance

Comparing Node.js vs PHP Performance

In the online development world, Node.js and PHP are some of the most popular platforms used.

PHP was first released in 1995, followed later by Node.js in 2009, and they are both mainly used as a server-side scripting language for developing web-based applications. However, Node.js is also starting to be used as a desktop application development platform.

PHP began as a dynamic language to update HTML pages with sytax similar to Perl, and started off as a rather basic programming language. Node.js used the already well-established JavaScript language and created a new development platform on top of the V8 JavaScript engine. Over time, PHP got more and more advanced programming features, such as an object-oriented programming model, namespaces, package management, and exceptions.

In this article, we will take a look at the performance differences between these two platforms, some popular PHP extensions to improve performance, such as the Zend JIT runtime and HHVM PHP runtime project, and some third-party benchmarks of these extensions.

The Basics of PHP and Node.js Performance

One area where there has been a healthy competition of sorts between PHP and Node.js is in the area of performance.

PHP – Interpreted Compilation

The standard PHP Zend runtime uses an interpreted compilation strategy, leading to less optimized code execution than a good JIT-(Just-in-Time)-based runtime.

Node.JS – Just-In-Time Compilation Using V8

Node.js uses Just-in-Time compilation with the V8 JavaScript Engine. This strategy for dynamically-typed languages has proven itself, but does often increase startup time a little.

Increase PHP Performance: OPcaching, JIT Compilation, and HHVM

Several popular extensions have been developed — designed to improve PHP performance.

OPcaching in PHP

Zend PHP 5.5+ also has a caching engine called OPcachewhich stores precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request. This is not as performant as JIT compilation but is a stable feature that is working now. You can enable PHP 5.5 OPcache if for some reason it’s not enabled by default (as it should be with PHP 5.5 or higher).

PHP Runtime Alternatives: HHVM & Hack

HHVM is an open-source virtual machine designed for running applications written in PHP and/or the Hack language.

HHVM uses a Just-in-Time (JIT) compilation approach to achieve better performance. Node.js also does JIT compilation using the V8 JavaScript runtime.

To make the most of the HHVM JIT compilation, it is important to put your code into functions, especially for the more time-consuming code parts.

The Hack language allows for performance improvements mainly due to these language features:

  • Async programming: Run separate blocks of code in parallel (using different threads)
  • Type annotations: Improve performance with a more predictable type environment

JIT Compilation in Future PHP Releases

There has been discussion and development to use JIT compliation in a future release of the PHP Zend runtime. JIT for PHP provides more than five times speedup on bench.php and as high as a 30 times improvement on some other specific benchmarks like Mandelbrot.

Multi-Tasking in Node.js and PHP

Node.js and PHP differ in their approach to concurrency, with Node.js using a non-blocking event loop (running in a single process) and the standard PHP Zend runtime using a blocking process.

For this reason, multiple PHP processess are often launched from the web server to be able to keep serving web requests. In Apache, you can set the maximum number of PHP processess allowed to run, and this works fine for many types of web applications.

Now, when the work being done in these processess tends to be long(er)-running, the server can quickly run out of available PHP processess. This will cause the HTTP request response times to increase, perhaps even to the point of requests timing out.

Web servers like Apache and NGINX have ways to improve the PHP multi-tasking performance to some extent, but these are more limited than true language support for multi-tasking.

There are several projects being worked on to make PHP asynchronous processing (multi-tasking) work better. The most popular is the HHVM project released in 2014 by Facebook; another project tackling PHP concurrency is pthreads.

Node.js vs PHP Performance Benchmarks

So what might these PHP extensions bring us in terms of performance compared to standard PHP or Node.js?

Let’s have a look at a few different benchmarks people have done.

Benchmark 1: Simple HTTP Requests

Click on the image to go to the benchmark website and see the full setup details.

Node.js vs PHP Performance Requests Per Second

Node.js vs. PHP performance and requests handled per second

Notes:

  • This HTTP-controlled “hello world” benchmark used Zend PHP 5.6.6 with OPcache enabled.
  • The test was done using the Apache ab benchmarking tool.
  • The performance of Zend PHP is less than half of Node.js.
  • The performance of HHVM is about 74% better than Zend PHP.
  • The performance of HHVM is very close to Node.js, but Node.js is still about 17% faster.
  • The performance increase when using WordPress with HHVM is about 47%.

Benchmark 2: HTTP + CPU tasks

Click on the image to go to the benchmark website and see the full setup details.

Node.js vs PHP Performance With CPU Heavy Task of Running a Bubble Sort

Node.js vs. PHP Performance with CPU heavy task of running a bubble sort

Notes:

  • This HTTP bubble-sort-job benchmark used Zend PHP 5.5.7 with OPcache enabled.
  • The PHP response times degrade rapidly after depleting the available PHP process pool (using a standard maximum of 250 processes on the web server).
  • The HHVM performance is similar to Node.js up to 1,000 sort elements, but with 10,000 sort elements, Node.js was about twice as fast HHVM (not visible on this chart).

Benchmark 3: CombSort Strict CPU Test

The following CombSort sorting benchmark is a strict CPU test.

The benchmark results:

CPU time System time RAM
PHP 5.6.4 102.69s 104.20s 2497508 KB
HHVM 3.5.0 12.56s 14.83s 362488 KB
Node.js v0.10.35 2.64s 2.64s 92240 KB

HHVM is seven times faster than plain PHP (by system time), but Node.js is more than five times faster than HHVM in this number-crunching test.

In terms of RAM usage, HHVM is much more efficient than PHP, but Node.js is even better.

Final Thoughts on Node.js and PHP Performance

For most PHP applications, HHVM clearly provides a significant performance boost thanks to the JIT compilation. The same will likely be true when the Zend runtime JIT feature is stable and released. How much the PHP JIT compilation improves upon the non-JIT PHP is also a matter of code organzation (especially the time-consuming code parts).

At best, HHVM is on par with Node.js, but in some cases, Node.js will clearly perform much better (e.g., for CPU-bound tasks). There are also more async code modules available for Node.js.

There is ongoing discussion about the future of the Zend and HHVM PHP runtimes. HHVM also looks to be getting even faster by using LLVM later this year.

If you are interested in monitoring your PHP application performance better, perhaps have a look at these performance dashboard solution providers:

  • New Relic: Allows you to track application issues like Apdex score, response times, requests per minute, and errors. After which, you can drill down to the code parts that are causing certain performance issues
  • DataDog: Offers real-time application metrics with an interactive dashboard
Roberto Sanchez

Questions or Comments? Ask Roberto!

Ask a question and Roberto will respond to you. We strive to provide the best advice on the net and we are here to help you in any way we can.

  • A$AP Mayonnaise {cracka}

    bullshit. hhvm is much faster than node.js

    • I’d be happy to see benchmarks to agree with you
      I agree any comparison can be biased depending on how benchmarks are done, so if you have seen other results, please share them with us.

      Note that results can occasionally depend on the OS, the server architecture, the storage type (HDD/SSD), the web server configuration, …

      It could also be interesting to see updated comparisons with the Zend PHP 7 engine & the last io.js fork which use a more recent V8 engine (now nodejs/node before merge back with joyent/node).

      Note also that scripts performances in both languages can depend on algorithm optimisation, like usage of asm.js patterns and/or Typed Arrays

      • frankel0

        We would also love to see more benchmarks. In house, we use both HHVM and NodeJS and they serve different purposes for us. We tend to go with NodeJS scripting when parallelization is of importance and go with PHP/HHVM for ease of use and we actually like PHP.

      • Jefferson González

        Is always fun to read articles like this but I did my own testing and here are the results. Spoiler: PHP was faster. (CPU: AMD FX(tm)-8320 Eight-Core Processor, RAM: 12G)

        Node v0.12.4, code:
        ———————————————————————–
        var http = require(‘http’);
        var server = http.createServer(function (request, response) {
        response.writeHead(200, {“Content-Type”: “text/plain”});
        response.end(“Hello Worldn”);
        });
        server.listen(8000);

        PHP v5.6.9 with opcache, fpm, hiawatha webserver, code:
        ———————————————————————–
        print “Hello World”;

        I did benchmarks with siege, and ran them on the same machine first.

        Node (siege -q -c 100 -b -t 60s http://localhost:8000/)
        ———————————————————————–

        [error] socket: -904210688 address is unavailable.: Cannot assign requested address
        done.
        siege aborted due to excessive socket failure; you
        can change the failure threshold in $HOME/.siegerc

        Transactions: 37370 hits
        Availability: 97.13 %
        Elapsed time: 7.13 secs
        Data transferred: 0.43 MB
        Response time: 0.02 secs
        Transaction rate: 5241.23 trans/sec
        Throughput: 0.06 MB/sec
        Concurrency: 83.33
        Successful transactions: 37370
        Failed transactions: 1105
        Longest transaction: 0.30
        Shortest transaction: 0.00

        As you can see had issues with nodejs not completing all transactions, So I had to run the benchmark on a external machine (ARM Odroid U2) connected to the same network. But first the PHP results when benchmarked on same machine.

        PHP (siege -q -c 100 -b -t 60s http://localhost/test.php)
        ———————————————————————–
        Lifting the server siege… done.

        Transactions: 842072 hits
        Availability: 100.00 %
        Elapsed time: 60.00 secs
        Data transferred: 8.83 MB
        Response time: 0.01 secs
        Transaction rate: 14034.53 trans/sec
        Throughput: 0.15 MB/sec
        Concurrency: 99.25
        Successful transactions: 842072
        Failed transactions: 0
        Longest transaction: 3.21
        Shortest transaction: 0.00

        PHP ran without issues and did a nice 14,034 Request/sec. Now the benchmarks ran on a external system due to nodejs failing if run on same machine. As mentioned before the external system is a small arm device called odroid u2 (CPU: 4 cores, Ram: 2G):

        Node (siege -q -c 100 -b -t 60s http://192.168.1.x:8000/)
        ———————————————————————–

        Lifting the server siege… done.

        Transactions: 157416 hits
        Availability: 100.00 %
        Elapsed time: 59.67 secs
        Data transferred: 1.80 MB
        Response time: 0.04 secs
        Transaction rate: 2638.11 trans/sec
        Throughput: 0.03 MB/sec
        Concurrency: 99.24
        Successful transactions: 157416
        Failed transactions: 0
        Longest transaction: 3.37
        Shortest transaction: 0.01

        PHP (siege -q -c 100 -b -t 60s http://192.168.1.x/test.php)
        ———————————————————————–

        Lifting the server siege… done.

        Transactions: 211041 hits
        Availability: 100.00 %
        Elapsed time: 59.19 secs
        Data transferred: 2.21 MB
        Response time: 0.03 secs
        Transaction rate: 3565.48 trans/sec
        Throughput: 0.04 MB/sec
        Concurrency: 99.23
        Successful transactions: 211041
        Failed transactions: 0
        Longest transaction: 3.03
        Shortest transaction: 0.01

        Conclusion? PHP (opcache) is faster than nodejs even without JIT. So I would advice everyone to test before assuming, and for people that does this kind of articles to share as much detail as possible of how they ran the benchmarks…

        • Jefferson González

          Bah, comment got truncated, anyway lets try to post it by part

          Edit: Fixed 🙂

        • Great job. Most work and business logic in web development is sequential and hence parallelism hardly a requirement, unless you are doing a chatting/server push application or a connected Single Page Application. Your results are an eye opener, even for a hello world scenario.

        • bmarkovic

          You do realize that opcache made sure nothing but the very string “Hello World” gets serverd by your PHP setup (print pretty much defaults to a few lines of machine code returning the string through, in your case, fastCGI pipe) whereas node actually had to do webserving itself (things like session handshake dealing with content type negotiations etc.). Much as no production PHP setup would nowadays be running (hopefully) without opcache, no node setup would serve simple static stuff (which a string is) through node itself. What you’ve actually shown here is that hiawatha was a better web server than node. Any web server (even Apache) is better than node, static content that needs no processing has always been served traditionally by nginx in the node world.

          • Jefferson González

            I don’t know what you mean by session handshake, the JS code I used isn’t dealing with any kind of sessions or SSL handshakes (since I didn’t did the requests using SSL), also content type negotiation? Thats pretty much handled here: response.writeHead(200, {“Content-Type”: “text/plain”}); and what that function does is add the header to the top of the generated response which is just plain text. What this means is that nodejs handles the request in a single pass… so again, not sure what you mean with session handshake or content negotiation. The http specification is pretty simple and consist of sending text…

            Also you say node isn’t used to serve a simple string? Then what is the web all about?

            On the other hand what you say about opcache is true to a certain degree, but doesn’t nodejs supports JIT which should be even more performant than opcache? Also nodejs should have the advantage on this test since just one component is used to render a simple hello world, which should have less overhead than hiawatha + fastcgi + php.

            Take for example openresty which embeds lua and is really fast instead of executing lua through fastcgi which would be slower… So arguing that nodejs is doing the whole work is a moot point. Nodejs may have the edge on number crunching right now over PHP, but real web applications spend most of the time rendering text (sending strings…?)

          • bmarkovic

            No web server handles any request with a single pass. I’m not talking about SSL session but OSI layer 5 sessions, and I’m not talking about HTTP content negotiation but OSI layer 6 content negotiation. All of this is handled by web server software, and is totally transparent for PHP developers and only slightly less than totally transparent in web development environments that expose HTTP (like node.js, C# etc). It however is all handled by the code inside the web server.

            Node is not a (terribly good) web server, it is however a very good application server. But to prove it’s worth it should be processing information. On CPU bound tasks, and even IO bound tasks node kicks even JITed PHP ass all over the place. Your example is a stretch in synthetic benchmark to prove some point that doesn’t exist. If you want to serve static content use something more appropriate, like nginx.

          • RLid

            I sure hope that Node has some advantage somewhere over PHP, otherwise what would be the point? Personally, I use Node for sockets. But *only* for sockets.

            That being said, I performed the “Benchmark 3” (calculations, combsort) on my computer, but I reduced the ridiculously high amount of sorted entries to 10 thousands (it was 10 millions entries!!). I left the source files of the test unchanged except for this hard-coded value.

            Here are my results (I ran the test 5 times and used the average value):
            Node 5.3.0 => 231ms
            PHP 7.0.1 => 128ms
            PHP 5.5.12 => 200ms
            Zephir (debug mode) => 131ms

            So… No, Node does not “kick PHP ass all over the place”, except if you deliberately use 10 millions of entries, which does not make any sense at all anyway.

          • bmarkovic

            Except that real web applications spend most of their time in I/O, and PHP is a blocking, synchronous I/O processor, which is handy if you’re lazy to wrap your head arond event-driven async coding, but gets slow if you’re being banged by a lot of requests.

            Which is why these synthetic benchmarks say fuckall about real performance of any runtime.

          • RLid

            So what you are saying is that no benchmark proving that PHP is faster than (or equivalent to) Node performance should be acceptable, but the other way around is great?

            “spend most of their time in I/O”
            Performing a SQL query taking 3ms to complete is clearly not a sufficient reason to claim that Node is the savior of all the Earth just because it is async.

            Plus, many async backend languages already existed before Node. Node is just JS, and precisely lazy people (because you brought that into the conversation) decided to use it, because they already knew a bit of that fuxked up language that JS is, and so they didn’t have to pull their head out of their a***** and learn a new, elegant, and performant language.

            So stop claiming empty things based on empty non-verifiable facts. Facebook has a LOT of requests to serve, and PHP is nice enough for them. Of course they built HHVM, but not because they needed “Node as an alternative to PHP”. They just needed a bit more raw speed (which has nothing to do with i/o and async, if you understand things well).

            Finally, people needing (as in life and death situation) async coding because otherwise they would fail… They don’t exist. There are just hipsters and fanboys who piss their pants in pride because they really think they are better than everyone else, that’s it.

          • bmarkovic

            Where to begin? For one, it’s not that PHP is a pinnacle of programming language design. It’s a lot more of a clusterfuck than JS. Second, no synthetic benchmark proves much about general case in any case . Third, async event driven design is natural to distributed systems. Finally, Facebook solved majority of their scaling issues long before HHVM and did so outside PHP. In the end, it’s Java and even Scala shops that are moving to node and that has fuckall to do with lazy front-end devs. WordPress cowboys are in a totally different ball game.

          • No, the opcache caches the compiled code, not its output.

          • bmarkovic

            Which for printing a literal string is nothing but that very string and very few lines of code sending characters down a pipe.

        • Ankit Pundir

          I am totally agree with your benchmarks, i did my own. between “hhvm server” vs “nginx with hhvm-fpm” vs “nginx with opcache with php-fpm”

          Found these :-

          Nginx with php-fpm with opcache faster on small app.

          Nginx with hhvm-fpm is faster on wordpress like medium size app.

          But nginx with php-fpm with opcache with php-phalcon is faster then any of these.

        • Sunny S.M Attwal

          Good Comment.. I appreciate

  • Thanks.
    In your WP test – did you try a complete WP caching solution? I talk about fully cached site

    • frankel0

      What does “fully cached” mean? Database cache, PHP Page Cache, Varnish, OpCache, etc?

      • Thanks for replying – really appreciates it.

        1. Well, I don’t think I fully understand the mechanisms
        2. But, if you bypass the PHP and WP code and only serve the final page from cache, what are the differences? Is Apache still involved in the WP case?
        3. I personally use W3TC for my WP site, with browser, page, object, database caches on, and CDN too.

        Let me know if it’s too much to ask

        EDIT: I’ll leave the question and research a bit more. I might get back with some questions later

        THANKS

        • frankel0

          Junky,

          It really depends on how deep you want to get into it. Personally, if you site is “mostly” static I would HIGHLY recommend trying to put Varnish in front of your WordPress installation.

          Basically, users would not hit apache or PHP at all and get pages served directly out of memory.

          We have an article on here on how to set up Varnish: http://www.hostingadvice.com/how-to/install-varnish-apache-ubuntu/

          I also wrote one that more specifically covers running Varnish in front of WP: http://ryanfrankel.com/using-varnish-with-wordpress/

          Now, this isn’t a trivial task but is certainly within most developers capabilities. The differences in page load times can be DRAMATIC (seconds to hundreds of milliseconds).

          • Hi frankel – thanks

            1.I’ve had the chance to get to know Varnish by now and indeed that’s a good option
            I think that even for more active sites with forums, it can be very useful, because even regenerating a bunch of pages every 10 seconds shouldn’t be that hard for good hardware, no?
            Indeed, it will become a problem with very active sites where regenerating rate can reach hundreds and thousands per 10 seconds (just a number). I don’t know what I would do in this case, but I have the feeling the node.js would have problems in this case too, unless optimized well for multi-threading and it’s fast enough (not even talking about DB/IO).

            I think Varnish is more or less what I was looking for

            2. A big mystery to me, still, is how do I know which hosting is good enough in terms of traffic and pings.

            3. I think I’ve tested few nodejs sites with webpagetest and they weren’t that fast compared to a well optimized static WP site (which really results in bypassing WP mostly)

            4. I wonder what will be the performance for a complex nodejs sites with some WP abilities

            Thanks!!

          • frankel0

            Junky,

            There is no reason you can’t put Varnish in front of a NodeJS server either. It really isn’t fair to compare a Varnish-cached site to any type of webserver that has to run any sort of processing.

            As for the hosting side, you can check out our reviews under the “Reviews” tab.

            It all really depends on what you are trying to do and the scale at which you are trying to do it. There are many fine PHP implementations of forums and I’m positive that Node could perform very well for ever the most active forums. In addition, we have only discussed caching at a page-level. There are many more fine-grained implementations that could boost performance if your pages truly are “dynamic”

            Maybe check out edge-side-includes as a start? Or think about storing results of some functions in caches. WordPress implements this in their “Transient API”.

            Hope that helps.

          • Yes, I understand that Varnish can be utilized with nodejs or anything else, theoretically

            And yes, your help and information and time and effort are much appreciated! many thanks

  • BruStack

    yeah, ok let’s GO

  • I want to know how Node.js is better than PHP.And How Node is more secure?

    • Secure? who mentioned secure? Having all requests handled within the same address space, indeed within the same address space as the socket termination, is hardly a recipe for Security. I would certainly expect node.js to degrade more progressively under heavy load than a multi process PHP environment but it wouldn’t be an architecture I would choose for for a site maintaining assets of any great value.

      • With the use of Angular and Ember js we can make it secure. Is not it?

        • Adding more code generally increases the attack surface.

  • Why Node.js response time is faster Than PHP response time?

    • Riey

      Here why:

      * On this test, PHP load a lot of modules that are ready to work, like ready to write on files, and show you the GET/POST/COOKIE variables, and connect to MySQL, and do other anything PHP is capable of doing. While Node.js is ready to do only basic JavaScript stuff and responding to HTTP requests.
      * Apatche’s default configuration is really suck, you lose a lot of performance only by allowing .htaccess.
      * Node.js focus on one request after the other, while PHP is multi-tasking, and of course you lose performance while multi-tasking.

      So long story short this kind of small tests are in favor of Node.js, those tests are a bit better https://www.techempower.com/benchmarks/.

    • When I clicked on the image there was no link to the methodology, but the results posted here do not illustrate a faster response time. They show greater throughput. These are often, but not always consistent – especially when comparing multi process daemons with event based + async io

  • RLid

    @roberto

    I can’t see the links to the full setup details. Could you please update your blog post?

    Thank you in advance,

  • Very good comparison – this one makes sense! 😀 Maybe it’s time for me to learn Go.

  • kyle morris

    Web servers like Apache and NGINX have ways to improve the PHP multi-tasking performance to some extent, but these are more limited than true language support for multi-tasking.

  • Noel da Costa

    Can you revisit this with PHP 7.0?

  • satya_123

    Yes. Like to know the benchmark with PHP 7.0. As per my knowledge it is even better than HHVM.

  • Mangap

    Please update the article PHP 7 already released and it much better. almost same as HHVM

  • Max

    This seems so sensacionalist. Benchmark with PHP 5.6 in 2016? Try with PHP 7 please 😉

  • Joey

    I use C and get 50000 requests per second, sometimes even more. I am left with more RAM than I know what to do with. Starting to look for bigger network pipes because it’s the main bottleneck. The number of servers needed is tiny. Other than redundancy or location (latency) most things are happy running on one server. Internally, many of the daemons I have written and designed do work similarly to node.js though. It’s not a bad methodology.

    I don’t really get why people don’t just use C. It’s so easy. The only drawback is that the libraries are highly distributed and not well centralised. Learning the build systems people have made is more difficult than learning C.

    • Hans Malherbe

      A couple of questions:
      1. Is it for dynamic non-trivial responses?
      2. Do you use HTTP Keep-Alive and pipelining? Without Keep-Alive my throughput drops to 5000 per second per core.
      3. What’s your architecture? Event loop, reactor, etc?
      4. Is your solution portable across *nix and Windows?
      5. Do you cache responses?
      6. How do you demux IO events? (IOCP, epoll, select)

  • rugsjunk

    You are comparing apples & steak. Node is an application (C++, wrapping javascipt), PHP is a language. There have been & are PHP projects, that are similar to Node in design (event loop listening on a socket, with thread pool)., as the OP mentions, the majority use pthreads.

    The fact that some business models can be written fullstack in Js, is causing this comparrison, and not applicable accross the board

  • Александр Литвинцов

    Hey granny, the article is so much late.
    PHP 5.6 was released 2 years ago . PHP 7 is 50% faster and in most case PHP7 is faster then HHVM and only 15% slower than Node.js.
    Of course it depends on benchmark algorithm. But with ordinary site code no difference between PHP 7 and Node.js.

  • Nemanja

    I did my own benchmark… app was little bit more complex than hello world, so nothing big, really.

    In order to make benchmark more comparable, I had fixed number of FPM workers to 1 (static FPM pool), since node is single threaded.
    Also, both application servers (PHP-FPM and Node.js) were behind nginx which served as front web server, with direct UNIX socket connection between web and app server in order to minimize TCP overhead in between.

    Results showed:
    PHP 7.0.x: 10K req/sec
    Node.js: 3K req/sec

    Tools used: wrk, ab, siege. They all showed very stable results each time.
    Above posted results are output from ab.

  • Serro Dot Exe

    ur test is wrong. http requests naturally favors java script

  • Michel Bosseaux

    please update with php 7 and node 6 (LTS) or 8 (0.10 is cleary past now).