首先,是个控制器,一般的标准的写法如下:
function index()
{
$query = $this->db->get('module_pages');
$links = '';
if ( $query->num_rows > 0)
{
foreach ($query->result_array() as $page):
$links .= '<a href="'.site_url($page['uri']).'">';
$links .= ucwords($page['title']).'</a><br />';
endforeach;
$data['links'] = $links;
}
for ($i=0; $i < 10; $i++)
{
$this->db->like('title', 'London');
$query = $this->db->get('module_pages', 1);
if ( $query->num_rows == 1 )
{
$row = $query->row_array();
$row['body'] = str_replace('Getting', 'booya', $row['body']);
$data['body'] = $row['body'];
}
}
$this->load->view('welcome2', $data);
}
视图文件类似以下:
<?=$links?>
<?=str_replace('booya', 'Getting', ucwords($body))?>
基准测试,默认的CI设置下,没有采用缓存等。结果是:Requests per second: 45.03 [#/sec] (mean)
还行,但是怎样才能更好呢?
把循环结果赋给变量
foreach ($query->result_array() as $page):
修改为:
$pages = $query->result_array();
foreach ($pages as $page):
Requests per second: 46.75 [#/sec] (mean)
不错,有了小小的进步。快了1.7请求每秒。
使用Memcache
用缓存对象的王者,Memcache。我们需要修改一下控制器的代码。
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$data = $memcache->get('view_data');
if ( !$data )
{
$query = $this->db->get('module_pages');
$links = '';
if ( $query->num_rows > 0)
{
$pages = $query->result_array();
foreach ($pages as $page):
$links .= '<a href="'.site_url($page['uri']).'">';
$links .= ucwords($page['title']).'</a><br />';
endforeach;
$data['links'] = $links;
}
for ($i=0; $i < 10; $i++)
{
$this->db->like('title', 'London');
$query = $this->db->get('module_pages', 1);
if ( $query->num_rows == 1 )
{
$row = $query->row_array();
$row['body'] = str_replace('Getting', 'booya', $row['body']);
$data['body'] = $row['body'];
}
}
$memcache->set('view_data', $data, false, 3600) or die ("Failed to save data at the server");
}
$this->load->view('welcome2', $data);
速度更快了,但是还是进步不是太多。怎样才能更快呢?
eAccelerator
添加eAccelerator扩展,确实好很多。还有吗?
CodeIgniter Output Cachining
CI的output cache使用比较容易
$this->output->cache(3600);
160.73 requests per second,已经有了很好的改善,但是我不会停止:)
Output Caching + eAccelerator
当她们同时启用时,Requests per second: 389.84 [#/sec] (mean)。
下图是这次测试的统计
codeigniter_benchmark_results |