I have an algorithm I need to speed up… Should I write a PHP extension?

The answer really depends on what kind of process it is.

If it is a long running process (at least seconds) then perhaps an external program written in C++ would be super easy. It would not have the complexities of a PHP extension and it’s stability would not affect PHP/apache. You could communicate over pipes, shared memory, or the sort…

If it is a short running process (measured in ms) then you will most likely need to write a PHP extension. That would allow it to be invoked VERY fast with almost no per-call overhead.

Another possibility is a custom server which listens on a Unix Domain Socket and will quickly respond to PHP when PHP asks for information. Then your per-call overhead is basically creating a socket (not bad). The server could be in any language (c, c++, python, erlang, etc…), and the client could be a 50 line PHP class that uses the socket_*() functions.


A lot of information needs evaluated before making this decision. PHP does not typically show slowdowns until you get into really tight loops or thousands of repeated function calls. In other words, the overhead of the HTTP request and network delays usually make PHP delays insignificant (unless the above applies)

  • Perhaps there is a better way to write it in PHP?
  • Are you database bound?
  • Is it CPU bound, Network bound, or IO bound?
  • Can the result be cached?
  • Does a library already exist which will do the heavy lifting.

By committing to a custom PHP extension, you add significantly to the base of knowledge required to maintain it (even above C++). But it is a great option when necessary.

One thought on “I have an algorithm I need to speed up… Should I write a PHP extension?

Leave a comment