uniqid() is slow

So there I was, profiling one of our systems with XHProf and what jumped out as taking up lots of wall-clock execution time? uniqid(). This function, which provides a convenient way to generate unique identifiers, can hold up your PHP execution far more than it should if you’re not careful.

Two things about uniqid() make it a potential performance minefield:

  1. If not called with a second argument of TRUE (the “more entropy” argument), uniqid() sleeps for at least a microsecond.
  2. uniqid() relies on the system function gettimeofday() — and the Linux kernel essentially serializes access to gettimeofday() across all cores.

Continue reading “uniqid() is slow”

Cross-domain communication with HTML5 postMessage

Plenty has been written about HTML5’s spiffy postMessage() method, which allows a window to send a text string to another window. When one of those windows is a web page in one domain, and another one of those windows is an iframe for a different domain embedded in the first window, you’ve got the basis for cross-domain communication that can work around the restrictions of traditional Ajax requests.

To take advantage of this capability, I put together a proof-of-concept jQuery plugin that makes this pretty simple.

Continue reading “Cross-domain communication with HTML5 postMessage”

Fast multiple string replacement in PHP

We added a language filter to Ning Pro last month. It lets Network Creators have naughty words (for the Network Creator’s definition of “naughty”) replaced with * characters.

A straightforward way to do this in PHP is to pass an array of words to look for and their replacements to a function like str_replace() or str_ireplace(). Or, similarly, use a regular expression that gloms the search terms together (and potentially checks word boundaries.) There are assorted WordPress plugins that work like this.

Continue reading “Fast multiple string replacement in PHP”

PHP Microbenchmarking

I’m pleased to announce the release of ub, a PHP microbenchmarking framework. You can download it from http://github.com/ning/ub.

The goal is to make it as easy as possible to compare the runtime of alternative approaches to the same problem, such as different regular expressions, or different methods for string or array manipulation.

Continue reading “PHP Microbenchmarking”