Monday, February 25, 2013

The Advnatages of Quercus PHP

While most everyone that uses PHP uses the Zend Engine, there are a few other PHP implementations.  One such interpreter is Quercus, a PHP interpreter written in Java and runs on the JVM within a servlet container.  Here are a few reasons to give Quercus a look.


1) Performance

So, is actually Quercus faster than Zend?  In some operations it is a bit faster, and in some operations it is a bit slower.  In general, I would say that Quercus PHP has about the same performace as Zend PHP for most PHP requests.  Quercus comes in 2 flavors, interpreted mode and compiled mode.  The interpreted mode is (in my epxierence) roughly comparable to not using a code cache with Zend, while the compiled mode is comparable to using a code cache with Zend.  See the following doc for an overview of Quercus performace.

While this does not seem like much of a "win" for Quercus, it is important to point out that Quercus is not slower for a standard PHP request.   If Quercus were slower, the following points would be rather moot.  However, Querucs is fast, and combinded with the following advantages, it is a platform to be considered for PHP devleopment.


2) PHP in the front, Java in the back

Different computer languages were written for different tasks.  PHP was written as a web app language and excels at formatting data for the presentation layer.  Java is great for creating data structures, algorithms, database connectivity, transactions, etc

The great thing about Quercus is it allows us to take advantage of both languages by using them seamlessly together: with PHP as the presentation of a Java based business tier.  With Quercus, you can write your data structures and business logic with Java, which then passes the results to PHP to be formatted and sent to the client.  This process is simple because Quercus PHP can seamlessly call Java objects/methods.   Using the best parts of both languages, one can do some really cool stuff.
  • Call Lucane, Hadoop, Cassandra (and more) directly from PHP.
  • Create complex and fast data structures in Java, which are then queried and displayed with PHP.
  • Application scope objects in PHP that are backed by Java objects.
  • Utilize the rich PHP web templating, with the vast array of Java middle-ware libraries.
  • Shared data structures between PHP and Java components of an application. 
  • Choose which parts of the application are best suited for PH P and/or Java
Quercus PHP is able to do the above because, of course, Quercus is ultimately Java.  For an introduction on using Java objects with Quercus, see this.


3) Database Connection Pooling.

One of the best features of Java  is database connection pooling.  Database connection pooling allows database connections to be managed by a pool that automatically grows and shrinks according to demand.  Connection pools save resources because database connections do not need to be constantly created/destroyed which has considerable overhead, particularly when done over remote connections.  Not only does this help the web layer, it also saves resources at the database layer because only a minimal amount of persistent connections need to be maintained.

Out of the box, Quercus allows the use of database pooling without having to change a line of php/mysql code!  Moreover, one can use PHP to Java integration (see point #2) to access Java objeccts backed by JDBC connection pooling.

4)  Scalable AJAX with PHP running on Java NIO

One of the problems with most setups of PHP is that there is one (thick) process attached to each request that blocks the process/thread until the response is sent.  On the other hand, Java has the option of using NIO (non-blocking IO) in the Servlet container.  This means that there is no longer a one to one ratio between requests and threads, but there can be many thousands of requests that are being severed by a small number of threads.  This is particularly good for AJAX, because many of those connections will be waiting for the next request within a keep alive.   By simply enabling an NIO connector, Quercus can scale to handle large number of non-blocking AJAX style requests in PHP.  No reason to turn down those keep alives!


5) Scalable COMET with PHP via Servlet 3.0 Async

 NIO's best friend is the Servlet 3.0 Asynchronous processing.  Putting this two technologies together allows a highly scalable COMET style app.  Servlet 3.0 Asychronous processing allows the requst thread to immedately return to the pool and allow another thread to handle the response.  This allows a single thread to efficiently pipe messages to many listeners.  Using this technology one can create scalable push notificaitons, chat rooms, and virtual worlds.  While the above point (#4) is seamless to the PHP developer, creating COMET with PHP will require extra coding, but nothing more than calling a few Java classes (see point #2).


6) Improved Session Management.

The standard PHP implementation places all session data on the disk, which can be quite slow.  Zend PHP does allow writing sessions to a database, however this requires quite a bit of work. One thing that Zend PHP cannot do is manage the sessions directly in memory.

On ther other hand, Java Servlet containers provide several configurable session options which can be easily taken advantage of with Quercus PHP, since sessions in Quercus are written on top of Java sessions.  The following options require only a change in the xml file.  Here are some options:
  • Memory - the defualt of most servlet containers is to store the session objects in memory.  This is very fast because it does not require disk access and serialization at every request.
  • Memory to Disk - this option access the sessions from memory, but then serialized them to disk after a period of inactivity
  • Memory to Database - smilar to above but backed by a database.  This is great for distributed sessions.    
  
7) Application Scope Objects

Because the standard implemenation of PHP is share nothing,  sharing objects between processes requires a external resource: APC object cache, Memcache, or writing the object to disk.  All these approaches share a common problems.  First, the objects need to be serialized/serialized frequently.  Second, there is no garnatee that two requests are referencing the same object.  This can occur if one process retreives the object, and starts processing while another process has updated the object.

For Java Servlets, Application scope objects objects are trivial.  Because they are kept in memory, cached objects do not need to be serialized and each servlet will always have a copy of the most recent object.  Using a Java backed object in Quercus PHP, application scoped objects are simple.  Ofcourse you could always serialize the object to disk/memccahe with Quercus just like you do with standard PHP, if that is what you desire.

Another option is to use the built in Quercus APC module.  This module works just like the normal APC and it is seamless to the PHP developer.

Saturday, February 16, 2013

Java vs PHP for MySQL Peformance

Java and PHP can both be used to connect to a MySQL database.  Yet, which language/platform has faster performance with MySQL?

I ran a quick benchmark to test them out.  As always, a benchmark is simply a benchmark, you will need to look at your own situation and your own use case.

The Setup

I took a very simple database which has one table with one row, defined as the following:

      create table test_table(id int, mytext varchar(50));
      create index indexTest on test_table (id);

I populated the table with 10,000 entries. We will test 2 things.  First,  we will test how quickly we can connect to the database and retrieve one value value.  Second, we will test how long it takes to iterate over a larger result set.

Tomcat was used as the java application server, and apache2 with mod_php prefork was used for PHP.  Linux was used and the database was on the same server as the app servers.  I did not measure the time for the http request, but the only the time it took to perform the database operations.  The database was warmed up for each test.

1) Connection Speed 

In this first test I tested the connection speed, closing the connection after each iteration.  Here are the averaged results.

     Java (no connection pool)  = 6 ms to connect to MySQL
     PHP = .46 ms to connect to MySQL

PHP is the clear winner here.  Compared to PHP, Java is just embarrassingly slow at creating a fresh database connection.

While Java is  slow at creating a fresh connection every time, one rarely does this with Java.  Instead, Java typically uses connection pools.  Connection pools allow database connections to be managed by a pool and shared among requests.  This prevents having to frequently open and destroy connections.  Using the Tomcat JDBC connection pool, Java is about 4 times faster than PHP.

     Java Connection Pool = .14 ms per connect


2) Iterating over a Result Set

In this next test, we want to see how Java and PHP compare while iterating over a result set.  1000 entries were selected, with each row extracted from the result set, like in the following:

Java
      String sql = "select * from test_table where id>0 AND id <1000";
      ResultSet rs = stmt.executeQuery(sql);
      while (rs.next()) {
            String s = rs.getString("mytext");
      }

 PHP
      $sql ="select * from test_table where id>0 AND id <1000";
      $result = mysql_query($sql);
      while ($row = mysql_fetch_array($result)) {
          $s=$row["mytext"];
      }

Here are the averaged results:

    Java = 2.3 ms to iterate over 1000 entries
    PHP = 4.9 ms to iterate over 1000 entries

So, Java is almost twice as fast at this test: faster but not too much faster.


Note about Persistent Connections and Thread Pools

While I did run the above test with a Java connection pool, I did not re-run the PHP test with PHP's persistence connection.  A persistent connection would likely have matched Java's speed, however I chose not to do this because it is often not recommended to use persistent connections in PHP.   Persistent connections are often not the standard way of connecting in PHP, however connection pools are standard way of connecting in Java. (for a larger discussion on persistent connections see this and this).   So, I wanted to compare the standard approaches in each respective language.

Moreover, while persistent connections are similar to Java's connection pools, they are not the same thing.  In PHP, a persistent connection is created for the apache process and re-used for each subsequent request on that process.  In this case, each apache process would have its own persistance connection.  So, if you have 50 apache processes, then you have 50 open connections.  That connection will stay open even if that process is not even using the database.

However, with Java connection pools, the number of open connections is not dependent on the number of request threads.  Instead, the pool starts with a small number of connections and grows and shrinks according to demand.  A request thread will obtain a connection from the pool only when needed.  Thus, you often need far fewer database connections than request threads. Under low load, the pool will shrink to one maintained connection (if so configured).


 Concluding thoughts

This test demonstrates that Java is a bit faster than PHP for establishing connections and iterating over results.  So which language/platform is better for MySQL? 

If the database on the same computer as the server, I would say that both languages are about equal.  Java is faster: 4 times faster creating connections and about 2 times faster iterating over a result set.  But, that is not drastically faster and will only occupy a small fraction of the entire database call and and even smaller fraction of and entire page request.

If the database is on a different computer then the server, then you will likely want to keep the connections alive between requests to avoid the overhead of establishing a remote connection.  Here Java's connection pooling has some real advantages over PHP's persistent connections, because the thread pool allows the connection pool to grow and shrink according to demand.  However, this concept was not benchmarked in this post, so I will leave this for a future discussion. 

Friday, February 15, 2013

Java vs PHP Memory Consumption

Does PHP/Apache take less memory than Java Servlets?

Often the answer to this question is yes.  PHPis rather light on memory and resource consumption.

However, I would argue that sometimes Java uses less memory than PHP under higher loads.  It is my experience that as the number of concurrent requests increases, you will reach a time in which Java uses less memory than PHP.  This happens because PHP and Java take a different approach towards handling server requests.

*Note that this post only deals with the "standard" or "common" setup of both PHP (using apache with mod_php) and Servlets (using BIO connector).  This post is an oversimplification of a very complex topic.

The Big Fat JVM.

The JVM often thought to be (and often is) a memory hog.  The JVM can easily take 100 MB of RAM and will happily consume as much memory as you are willing to give it (this rapid consumption of allocated memory is a feature that allows the garbage collection to be run less).

However, when we  look at the JVM and the memory it consumes, we have to realize exactly what it gives us. Within that single JVM process you are running the following:
  1. App Web Server (such as tomcat).  The server runs within the JVM process and is not a separate process.   A startup Tomcat will only add a few megs to the memory heap.
  2. Code Cache:  this space holds the compilation of bytecode.  JSP/Servlets are not recompiled at every call, but held in the code cache.  For php this is often a separate module or extra install, but in Java it is built into the JVM memory space.
  3. Application Scope Objects : the ability to store large data objects.   In PHP this requires an addition module or process such as APC or memcache to store objects.
  4. Database pooling :  Database connections are not constantly created and destroyed (which creates overhead), but are shared among requests in a pool.  Shared connections often means less connections.
  5. Request Threads : In Java, the threads that handle http requests are not separate processes, but lightweight threads that run within the single JVM memory. This is most important for memory consumption.
As you can see, the JVM provides many features out of the box that would require a host of additional processes and/or modules for an equivalent PHP/Apache setup.


PHP: The little processes add up.

The last point above is really the most important, Java and PHP take a different approach to how each http request is handled.

Lets first take a look at php.  PHP forks (assuming pre-fork)  an apache process for each request.  Each apache process has its own memory space and loads all modules, the interpreter, php files, byte code, database connections, and application stack/data.   The more modules, bytcode, application memory, etc... the larger each of these processes will be.

Each process typically takes 5-30 MB, depending on how much is loaded in.  People running PHP sites often see around 20 MB per apache process (see here and here).

So, if you have 1 GB of memory allocated to these 20 MB apache processes, you can run about 50 concurrent connections.  And then you will need extra memory to run databases, APC cache, Memcache, etc.

Java: Big JVM with small request threads.

So the JVM is a big ship, but it is a ship with a lot of inertia. Lets see how a java request is handled.

When a request comes in, it is not handled by a separate process, but by a small lightweight thread.  These threads, by themselves, add almost nothing to memory, except a small (configurable) stack size and a small amount of memory added to the heap.

Unlike PHP, each thread does not need to have its own copy of files, bytcodes, compiler, runtime, databaese connections, etc, because these are all shared within the single JVM process.  Each request thread is cheap!  Thus, while it it takes quite a bit of memory to get the JVM started, each additional concurrent connection requires far less memory.

So, assuming that you had 1GB allocated for tomcat and each request thread takes about 3MB ( assuming about 1MB thread overhead  with 2 MB application data) and that the JVM aside takes around 100 MB. In this situation, you can run about 300 concurrent connections.   You can play with you own numbers to get your own estimated number of concurrent connections.


Who really cares, request times are so short, so we don't need many concurrent connections.

But the point is that it does matter.  Even if your requests are short, keep-alives will persist your connections.  A keep-alive will keep the entire process/thread until the timeout.  So if you have a keep alive of 10 second with 50 users are clicking around fairly often, then you will have 50 processes/threads alive at all times.  For small threads, this is not a big deal.  For bigger processes, this is a big deal.

You can alleviate this by removing or drastically reducing keep-alives, but this really only becomes a problem because of process size.  If one were using a thread model, one would not have to cut the keep-alive to a ridiculously small time -  which is particularly important for high response time for ajax style apps.

Give it a test.

Spin up a small VPS.  Create equivalent tests in php and java. Slam it with a testing program with keep-alives.  See which one starts thrashing the swap first.

Concluding thoughts.

This might have sounded like a knock against PHP, which it is not.  It is simply pointing out the differences between how the two web app platforms work.   Often php will require much less resources for smaller load applications.  And PHP can clearly scale (horizontally and vertically) to accomplish most any web app necessary.

However, it is my experience that as the number of concurrent requests increases, you will reach a time that Java will use less memory than PHP/apache.   Moreover, this fact is not the only (nor the primary) factor when choosing a language for a project, just something to think about.

Thursday, February 14, 2013

Pointers to Functions in Java


It is often thought that the Java language does not have pointers to methods.  In some sense it is true, but the feature is kind of there – it is just a little trickier to use than other languages.
Java method pointers comes via reflection and the ability to have a reference to a method. Given a particular class, one can grab a reference to methods of that class. These methods can then be passed around and invoked - as one would expect with pointers to methods.

Let's see how this works, say we had a class Person defined as such and we want to pass around specific methods of this class.

public class Person {
    String firstName, lastName;
    int age;
    public Person(String f, String l) {
        firstName=f;
        lastName=l;
    }
    public String getFullName() {
        return firstName + " " +lastName;
    }
     public void setAge(int age ) {
         this.age=age;
    }
}



Getting a method from a class:

Using reflection we can obtain a method of a class by calling the getMethod() of a class, which can then be invoked  For example:

[1]    Person p = new Person("Geroge", "Washington");
[2]    Method method = Person.class.getMethod("getFullName");
[3]    String s  = (String) method.invoke(p);
[4]    System.out.println(s);

Lets break down the code.  Line one creates the an instance of the object.  Line 2 gets a reference to a method of the class person.  This is how we get a reference to a method!!  Line 3 invokes that method on a particular object (p), and finally we print out the results 


Handling Method Parameters and Arguments

The above method had no parameters.  Things get a bit more complex when we have to deal with method parameters.

Method method = Person.class.getMethod("setAge", int.class);
method.invoke(p, 33);

If the method has parameters, we need to tell Java "which" method we want, as there can be multiple methods with the same name but different parameters.  We let Java know which parameter in getMethod by supplying an array (or sequence) of "Class" types.  In this case, the method setAge takes an int, so we supply the class of int, which can be obtained by through int.class.  If it took a String we would use String.class

What if there were two arguments to that method?  Imagine there was a changeName method to class Person that took a new first and last name, we would obtain that method with the following call:

method = Person.class.getMethod("changeName", String.class, String.class);
method.invoke(p, "Thomas", "Jefferson");


Where to go from here?

Once you know how to grab a method of a class/object, you can do lots of interesting stuff.  You can pass method reference around between methods, you can store the methods in data structures to be invoked at another time, etc.

But in order to be effective at using method references in Java, you need to have a solid grasp of Reflection in Java.  And you will likely want to wrap the method references in a layer of abstraction, as the reflection classes are a bit cumbersome.

Check out some of the core docs:

- the Class docs 
- the Method docs