Chris Miller
Chris Miller

Reputation: 763

How can I optimize this code snippet to execute faster and with a smaller footprint?

We have a small script that uses memcache to track concurrent sessions, with the client making a new request every 10-seconds to "renew" its session and also get the latest count of users online.

$session    = $_GET['session'];
$streamid   = $_GET['streamid'];

if(!is_null($session) && !is_null($streamid)) {
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211);

    $data   = $memcache->get($streamid);

    if($data === false) {
        $data   = array($session => time()+10);

        $memcache->add($streamid,$data,0,10);
    } else {
        $now            = time();
        $streamCount    = count($data);

        for($i=0;$i<$streamCount;$i++) {
            if($data[$i] > $now) {    
                    unset($data[$i]);
            }
        }

        $data[$session] = time()+10;
    }

    echo count($data);
} else {
    echo 'no session or stream specified';
}

Upvotes: 0

Views: 106

Answers (1)

Amir Raminfar
Amir Raminfar

Reputation: 34179

Have you tried running this yet? Do you need to optimize it? Maybe it works like how you want it right now. It seems like a better solution would be to decouple it and write it as clean as possible. Put timers around calls and if you see something being slow then try to fix that code. Don't optimize if you don't need to.

Upvotes: 2

Related Questions