views:

175

answers:

2

In PHP+MySQL+PDO, would it be much slower to do

  • Get an item's ID by name
  • Get item data by ID

than to just

  • Get item data by name

The latter is only one query, so obviously faster. The former makes for cleaner code though (because the item's ID is often also just known beforehand), so it would be better if the performance difference is small enough.

The code where I'm using this:

public function actionView() {

    // read http request
    ...

    // get item
    $itemModel = new Rust_Model_Item();
    try {
        $id = $itemModel->getItemIdByUrlTitle($urltitle);
        $item = $itemModel->getItem($id); // lots of data
    } catch (Rust_Model_Item_NotFoundException $e) {
        throw new FastMVC_Web_Error(404, 'Item not found');
    }

    ...

}

http://code.heukelom.net/filedetails.php?repname=rust&path=%2Ftrunk%2Flib%2Fclasses%2FRust%2FController%2FItem.php

public function getItem($id) {

    $item = $this->getItemBasics($id);

    $catModel = new Rust_Model_Category();
    $item['category'] = $catModel->getById($item['category_id']);

    $ratingModel = new Rust_Model_Rating();
    $item['rating'] = $ratingModel->getForItem($id);

    $pageModel = new Rust_Model_Page();
    $item['pages'] = $pageModel->getListForItem($id);

    $tagModel = new Rust_Model_Tag();
    $item['tags'] = $tagModel->getForItem($id);

    return $item;

}

http://code.heukelom.net/filedetails.php?repname=rust&path=%2Ftrunk%2Flib%2Fclasses%2FRust%2FModel%2FItem.php

+2  A: 

You should design your query so that the fields that you use in your WHERE clause have proper keys and indexes set-up on them, and only use one query to select them.

duckyflip
+1  A: 

Why not create a single query that gets the item data by id, putting an index on the id.

northpole
Though if he put an index on the name also, then he could pick which one to use, depending on the situation.
James Black
Because of the way I'm putting the data access parts in my functions. I have a pretty large function which does the getting item data by id. Somehow it feels less clean to expand that function to work with name (and who knows what other future condition) too. Regarding clean code, it would be better to select the id first, then the data. I'm just worried about performance.
Bart van Heukelom
If you are fetching object members on-demand from the database, consider using some form of 'usage id' identifying the caller (__LINE__, __FILE__ might help). Do a per-member fetch but cache the ones they used. This way you can preload them next-time and per-access fetch others that appear because of control-flow
Aiden Bell