?

Log in

No account? Create an account

Switch vs Array in PHP

« previous entry | next entry »
Aug. 14th, 2007 | 01:09 pm
location: In front of the computer
music: Cartoons

I did some benchmarking for a script I was writing, to see how switch performs in php. I did 4 runs of the script for each version, taking the lowest timing each time. I tested with 10, 20 and 30 switch cases, and with 10, 20 and 30 array elements. Results and script (for 10 cases) is below.

The results show that using an array is faster in every case, although the difference is minimal for 10 cases. At 30 cases, the array clearly shows better performance than the switch. Of course, things may be different if the cases were triggered more often, or if I wanted to do something useful inside every case. But that's not the situation I was interested in for these benchmarks.

# Switch:
# 1.288s with 10 cases
# 2.192s with 20 cases
# 3.048s with 30 cases

# Array:
# 1.104s with 10 cases
# 1.108s with 20 cases
# 1.120s with 30 cases

do_array();

function do_switch() {
  for ($i = 0; $i < 500000; $i++) {
    switch($i) {
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
      case 8:
      case 9:
      case 10:
        nothing();
    }
  }
}

function do_array() {
  $arr = array(
    1 => true,
    2 => true,
    3 => true,
    4 => true,
    5 => true,
    6 => true,
    7 => true,
    8 => true,
    9 => true,
    10 => true,
  );
  for ($i = 0; $i < 500000; $i++) {
    if ($arr[$i]) {
      nothing();
    }
  }
}

function nothing() {
}

Link | Leave a comment |

Comments {0}