Monday, July 23, 2007

the root of all evil

Alright, it's not all that evil, but I'm looking at this PHP code:


$message = 'Hi, ' . "\r\n";
$message .= "\r\n";
$message .= 'Your account at ' . $this->domain . ' is awaiting activation.' . "\r\n";
$message .= "\r\n";
$message .= 'To activate your account, please visit ' . $this->domain . '/members/activate/' . $activation_key . "\r\n";
$message .= "\r\n";
mail($to, $subject, $message, $headers);


And I'm thinking,

  • mixing single quoted strings and double quoted strings.
  • mixing single quoted strings, double quoted strings, and concatenating variables instead of putting them inline


I don't care too much about the strings being hardcoded, the app doesn't need to be multilingual, yet. But I'm struck by the fact that in the attempt to optimize (in PHP, single quoted strings are faster than double quoted strings since the runtime doesn't need to try to do string interpolation (parse the string to find variables, and replace the variables with their values).

On the other hand, this code is going to send mail. This is a classic too early optimization. The network will be the bottleneck, or writing the file will be the bottleneck (if we write the emails into a file first for batch sending later [which isn't relevant for the concrete case, the email is sent immediately, see the mailto(...) function call]). And it's harder to read (mixing two kinds of strings always is, and in fact the code is mixing three kinds of strings, the third being variables. Code for maintainability first, code for performance only after profiling and finding the hotspots in the code.

No comments: