Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nadeem-khan/a907466353397d0a1ea2 to your computer and use it in GitHub Desktop.
Save nadeem-khan/a907466353397d0a1ea2 to your computer and use it in GitHub Desktop.
Coding Tips for Speeding up Codeignitor Performance

Best way to use data fetched from DB with result_array()

$result = $this->db->get()->result_array(); // result_array() itself uses a for loop so we actually end up looping twice in the next line
foreach ($result as $row)
{
  ...
} 

Instead use:

  $result = $this->db->get();
  while ($row = mysql_fetch_assoc($result->result_id))
  {
    ...
  } 

Optimization Tips

1- Check for worst performance killers first (which are mostly loops and database queries / forgotten indexes)
2- Next come functions (refactoring)
3- Change tiny pieces like: $count vs count() in for loops? Single vs double quotes? ++$i vs $i++? fetch_assoc() vs result_array()? 

$this->db->count_all_results() vs $this->db->get()

 $this->db->count_all_results() replaces $this->db->get() in a database call.

 I.E. you can call either count_all_results() or get(), but not both.
 
 // num rows example
 $this->db->select('*');
 $this->db->where('whatever');
 $query = $this->db->get('table');
 $num = $query->num_rows();
 // here you can do something with $query

 // count all example
 $this->db->where('whatever');
 $num = $this->db->count_all_results('table');
 // here you only have $num, no $query

Only Load What You Need

Ideally never load anything unless you are going to use it in the code that is running.

 class Welcome extends CI_Controller {
  public function __construct()
  {
      $this->load->library('email');
      $this->load->library('ftp');
  }
  public function index()
  {
      $this->load->view('home_page');
  }
}
 In the example above we are loading two libraries that will never be used when viewing the home page so by including them we are just wasting resources.

Replace DB Calls in Foreach loop with a single call

$data = [];
foreach ($ids as $id) {
    $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` = " . $id);
    $data[] = $result->fetch_row();
}

But the same thing can be accomplished much more efficiently in a single SQL query as follows:

$data = [];
if (count($ids)) {
    $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` IN (" . implode(',', $ids));
    while ($row = $result->fetch_row()) {
        $data[] = $row;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment