For table rows an odd/even style is often used. A repeated test for odd-/evenness would seem time consuming and different runtime environments have different optimisations. In PHP the following two functions have been performance tested rigorously:

function is_odd1($num){
  return ($num&1);
}

function is_odd2($num){
  return ($num % 2 == 0);
}

The latter is mostly used in Drupal. It appears that broadly speaking the former function is superior. However, for realistic values, say in the order of 100, the latter is about 20% to 30% faster and consistently so.

Comments

James Andres’s picture

Hi figaro,

That's interesting :-).

Unfortunately, Drupal has way bigger bottle necks that the Core devs will likely pay more attention too ....

C'est la vie,

James Andres

Lead Developer on Project Opus
www.projectopus.com

kbahey’s picture

Just for fun, I tried this code:


include 'includes/bootstrap.inc';

function is_odd1($num){
  return ($num&1);
}

function is_odd2($num){
  return ($num % 2 == 0);
}

echo "odd1 ";
timer_start('odd1');
for ($i = 0; $i < 1000000; $i++) {
  is_odd1($i);
}
$stop = timer_stop('odd1');
echo $stop['time'] ." ms\n";

echo "odd2 ";
timer_start('odd2');
for ($i = 0; $i < 1000000; $i++) {
  is_odd2($i);
}
$stop = timer_stop('odd2');
echo $stop['time'] ." ms\n";

odd1 1221.76 ms
odd2 1119.47 ms

$ bc
scale=2
1119.47/1221.76*100
91.00

So, there is a 9% difference, but the latter is faster.

For the real bottlenecks, check this post by Dries on the database interaction layer. There are other bottlnecks in certain queries perhaps, but this one focuses on the PHP side of it.
--
Drupal development and customization: 2bits.com
Personal: Baheyeldin.com

--
Drupal performance tuning and optimization, hosting, development, and consulting: 2bits.com, Inc. and Twitter at: @2bits
Personal blog: Ba

AjK’s picture

It's worth noting that the PHPTemplate engine already provides the $zebra variable for alternating row styles. If a modulus is being used in various places then the "performance hit" isn't in the code as such, it's in repeatedly re-inventing the wheel when a variable exists to do the job already.

best regards,
--AjK