I am using CDbHttpSession as the post http://programmersnotes.info/2009/03/05/speeding-up-yii-or-why-should-you-use-db-sessions/ suggest
'session' => array(
'class' => 'CDbHttpSession',
'connectionID' => 'db',
),
But I found the slowest part is the session table part, the call to Yii::app()->user->isGuest takes a lot of time working on session table:
[0.77831] system.db.CDbCommand.execute(DELETE FROM YiiSession WHERE expire<1263576215)
[0.00112] system.db.CDbCommand.query( SELECT data FROM YiiSession WHERE expire>1263576216 AND id=:id )
Analyze shows it is round [color="#8B0000"]407ms[/color]
EXPLAIN ANALYZE DELETE FROM YiiSession WHERE expire<1263576215
Seq Scan on yiisession (cost=0.00..88.69 rows=1 width=6) (actual time=0.383..0.383 rows=0 loops=1)
Filter: (expire < 1263576215)
Total runtime: 0.407 ms
SELECT count(*) from YiiSession
1435
[size="5"]Fix Part 1: add Index[/size]
CREATE INDEX yiisession_expire_idx ON "yiisession" (expire);
Analyze shows it is round [color="#8B0000"]49ms[/color]
EXPLAIN ANALYZE DELETE FROM YiiSession WHERE expire<1263576215
Index Scan using yiisession_expire_idx on yiisession (cost=0.00..8.27 rows=1 width=6) (actual time=0.026..0.026 rows=0 loops=1)
Index Cond: (expire < 1263576215)
Total runtime: 0.049 ms
[size="5"]Fix Part 2: why clean session for every visit? [/size]
CDbHttpSession.php
public function openSession($savePath,$sessionName)
{
$db=$this->getDbConnection();
$db->setActive(true);
if($this->autoCreateSessionTable)
{
$sql="DELETE FROM {$this->sessionTableName} WHERE expire<".time();
try
{
$db->createCommand($sql)->execute();
}
catch(Exception $e)
{
$this->createSessionTable($db,$this->sessionTableName);
}
}
return true;
}
Why autoCreateSessionTable will clean session table? Any why always do the cleanup? I think [color="#8B0000"]it is a bug[/color].
Before qiang fixed it, I disable autoCreateSessionTable
'session' => array(
'class' => 'CDbHttpSession',
'connectionID' => 'db',
'autoCreateSessionTable' => false,
),
Now page load is [color="#8B0000"]less than 100ms[/color]