Saturday, March 16, 2013

Quercus PHP: interpreted vs compiled

The good folks at Caucho were nice enough to send me a trial key for Quercus PHP Professional, so I gave it a spin this morning.

Quercus PHP is an implementation of PHP that runs on the JVM.  The open source version runs in interpreted mode, while the Pro version compiles the PHP to Java byte code.  The Pro version is not free, but costs $99 a year for a license.

Three Ways to Run Quercus PHP:  As I see it, there are 3 ways to run Querucs, and your choice would depend on your use case and needs.

A) Compiled Mode -  Compiled mode is only available in Quercus Pro ($99), but this will give you the fastest speed.  The PHP script is compiled to Java classes, which yields not only fast PHP execution, but also leads to high performance integration with existing Java code.  The only downside of this mode is that static strings are stored in the PermGen space.  This is not necessarily a bad thing and this works the same way as JSPs, but it just something to be aware of when you are allocating space and re-deploying apps.

B) Interpreted Mode - In this mode, the PHP pages are interpreted at each request.  This is still very fast, and very similar in speed to mod_php without APC.  In this mode, the PHP file is cached, so there is no need to re-read the PHP from disk IO.  You can adjust the size of the PHP page cache.

C) Interpreted with No Page Cache - This mode is the same as the above, except it removes the page cache of the PHP file.  This mode is very similar to mod_php in that each PHP file is re-read from disk at each request.  Most people would want a PHP page cache, but there are times when you may not want it because it will consume extra memory to keep those pages in the cache.  On a memory restricted sites, with lots of different PHP pages in which each page (in of itself) is accessed rarely, you may want to disable the page cache.

Quick Performance Test

I ran a quick benchmark to see how the different Querucs modes perform.  I grabbed a PHP benchmark from this site.  This is a rather long running script, so it does not measure requests per second, but rather the time it takes to execute and entire script.  Tomcat 7 was used as the Java server.  I ran the scripts a number of times and averaged the results:

quercus compiled - 3247 ms
quercus interpreted  - 7540 ms
quercus interpreted no page-cache -7798 ms
apache mod_php - 9088 ms
apache apc  - 9159ms

As we can see Quercus in compiled mode is almost 3 times faster than Apache mod_php, and Quercus interpreted is a bit faster as well.

Since this is a long running script, the page cache did not really help the interpreted mode of Quercus.  Similarly APC did not help mod_php, because the compile time is a small fraction of the running time.

We should not conclude too much from this quick test, but it seems to be in line with some of the results found on the official Quercus page.

Saturday, March 9, 2013

MVC using Servlet with a Quercus PHP view

In this short post I will briefly explain how to create an MVC system that uses a Java servlet as the control and model, and a PHP page as the view.  We will use Quercus PHP, the great implementation of PHP that runs inside the JVM.  This tutorial will assume that you know how to setup and use both Java sevlets and Quercus (simply google them if you do not know, or send me a note).

This post will build off of the classic Servlet/JSP MVC examples, as seen in tutorials like this.  But instead of using a JSP to view the model, we will use PHP.  So, really this just boils down to how you can pass a Java object to PHP.

Lets start with a simple servlet that contains this code in the process request:
            request.setAttribute("message", "hello from java to php");
            request.setAttribute("number", 100);
            RequestDispatcher dispatcher;
            dispatcher=request.getRequestDispatcher("/view.php");
            dispatcher.forward(request, response);
Ok, this code should be familiar, we simply place two objects inside the request and the forward the request dispatcher to a PHP page called 'vew.php' (instead of a jsp page).  Now lets look at the PHP code.

The first thing we want to do in view.php is grab the Java request object, so we can grab the objects we placed in the request.  Quercus provides the PHP function quercus_servlet_request() to do just this.  Then I add a function to make it easier to get the object attributes out of the request.  It is a good idea to put this code in a global include:
        <?php
             $request = quercus_servlet_request();
             function getAttribute($key) {
                  global $request;
                  return $request->getAttribute($key);
             }

         ?>

Now, within PHP we can call the above function to get the Java objects, and use PHP as the view component of the MVC. Piece of cake!
       <?php
            $message = getAttribute("message");
            echo "message = ".$message."<br>";
           $number = getAttribute("number");
           echo "number = ".$number;
       ?>

Friday, March 8, 2013

Tips for Unity3D mobile development

There have been several articles written how to optimize Unity3d for mobile development.  Most of those articles focus on draw calls, polygon reduction, texture atlases, etc.  Those are all great topics, but I wanted to pass on a few more tips.  Enjoy!


1) Favor cookie-cut geometry over cookie-cut textures.

As it is well known, mobile devices are not optimized for handling textures with transparencies.  Instead of having a cookie-cut alpha channel on a textures, it is often possible to achieve similar results by simply increasing the geometry. 

For example, if you needed to create a "star" you could use a 2d plane textured map with a an alpha-blended or cut-out image of a star.  Alternatively, you could model the outline shape simple star (a few more polygons will do the trick) and then apply a non-transparent texture.  In this second way, the geometry provides the cookie-cut.  While this technique is not appropriate for all cases, it does often work well and leads to higher performance, because mobile devices are optimized for polygons not transparent textures.


2) Use a texture atlas for in game text.

Never use text GUI elements during gamlay, and try to avoid Text3D/Mesh (as they use transparencies).  Instead, when possible, using an opaque texture atlas.  For example, in our recent game we wanted to display the number of coins the user has collected.  So we created this texture atlas.

By dynamcailly moving the UV coridatnes on a set of rectangle polygons, we were able to achieve much faster frame rates than if we were using text3d or text meshes.  It is a bit of work to set this up, but it is worth it (assuming you do not need transparent text).   To change the UV coordinates:

        // Grab the mesh first
        Mesh mesh =gameObject.GetComponent<MeshFilter> ().mesh. 

       //Create an array of uvs... set them to be whatever you want
       Vector2[] uvs = new Vector2[4];
      
      // Apply the UVs to your mesh
      mesh.uv = uvs;


3) Avoid objects GameObjects with attached Behavior scripts

The easiest way to attached code to an GameObject is to attach a MonoBehavoir script.  However, this comes with a performance penalty.  Instead, I would recommend limiting the number game objects that have attached scripts.   In fact, in many cases you can almost do away with MonoBehavoir scripts, aside from a a few "main" scripts that load the objects and gets things initialized.

For example, consider creating a custom star field that has hundreds of stars.  To create this, you could have hundreds of GameObjects with attached behavior scripts.  But this would come with quite a performance penalty. 

Instead, you could have a single behavior script that contains an array of GameObject Transforms.  This single script simply moves the transforms of each star at each frame.  This approach saves memory and saves cpu cycles.  Coupled with a nice object orientated design, you can take this same approach and extend it to most objects in your scene.


4) Look for the "new" keyword and avoid it when possible

The "new" keyword allocates a new object on the heap (or stack if a struct).  This operation is a bit expensive, and if used frequently will force frequent garbage collection.  Clearly we need to use "new" to get new objects, but avoid creating new objects within functions that are called at each frame.  If it is being called each frame, there is no reason to construct a new object each time.  Create the object once, in the start() or constructor, and then re-use it.   Some might consider this over optimization, but I consider it smart game programming.  It is a simple paradigm to follow and will drastically improve game performance.