Posts

Showing posts with the label Java

For or Foreach? PHP vs. Javascript, C++, Java, HipHop (update: HHVM v2)

Lessons learned: Foreach is 4-5 times faster than For Nested Foreach is 4-5 times faster than nested For Foreach with key lookup is 2 times slower than Foreach without C++ is 60 times faster than PHP running For/Foreach on Arrays Javascript is 2-20 times slower than C++/Java running For on Arrays HipHop is currently no alternative to C++ Using a better CPU makes the code 4-5 times faster Here is a sample script, running on a 1.4 GHz machine with PHP 5.4.0: // init arrays $array = array(); for ($i=0; $i<50000; $i++) $array[] = $i*2; $array2 = array(); for ($i=20000; $i<21000; $i++) $array2[] = $i*2; // test1: foreach big-array (foreach small-array) $start = microtime(true); foreach ($array as $val) { foreach ($array2 as $val2) if ($val == $val2) {} } echo (microtime(true)-$start)."\n"; // test1b: foreach big-array (foreach small-array) $start = microtime(true); foreach ($array as $val) { foreach ($array2 as $val2) if ($val === $val2) {} } echo (microtime(true)-$st

How to implement a real-time chat server in PHP using Server-Sent Events (update: added C benchmark)

Lessons learned: A web server written in PHP can give more than 10000 req/s on small hardware A web server written in PHP is not slower than being written in Java (without threads) A web server written in PHP is 30 percent slower than being written in C (without threads) Realtime applications can be developed in PHP without problems PHP normally runs inside a web server like Apache or nginx. This keeps all requests separate from each other and does not allow sharing memory or connections. To implement a chat server, the browser has to poll the server regularly for new data. The data is stored in a database and looked up for each request. This is very slow, takes a lot of resources on the server and does not give messages in realtime. Newer browsers support data being pushed from the server to the client. There are two techniques used: WebSockets (full-duplex) and Server-Sent Events (push notifications) Using these techniques, one connection stays open for each client and the server