0

Task: get display 10 objects except 1 specific Solutions:

  1. get 11 objects from DB, and do something like this

    foreach ($products as $product) { if($product->getId() != $specificProduct->getId()){ //display } }

  2. just add condition in sql query WHERE p.id != :specific_product_id

Some additional information: we use doctrine2 with mysql, so we must expect some additional time by hydration. I have made some test, I timed both of this solutions but I still haven't any idea which way is better.

So, I have gotten some strange results by my test(get 100 queries with different parameters)

  • php = 0.19614
  • dql = 0.16745
  • php = 0.13542
  • dql = 0.15531

Maybe someone have advice about how I should have made my test better

3
  • 2
    do as much as you can in the SQL... it makes life a lot easier... Commented Oct 18, 2013 at 22:56
  • in SQL it would be <> Commented Oct 18, 2013 at 23:02
  • @tereško, almost every SQL implementations supports both forms of "not equal" -- see Should I use != or <> for not equal in TSQL? Commented Oct 18, 2013 at 23:03

3 Answers 3

3

If you're concerned about the overhead of hydration, keep in mind that doing the != condition in PHP code means you have to fetch thousands of irrelevant, non-matching rows from the database, hydrate them, and then discard them.

Just the wasted network bandwidth for fetching all those irrelevant rows is costly -- even more so if you do that query hundreds of times per second as many applications do.

It is generally far better to eliminate the unwanted rows using SQL expressions, supported by indexes on the referenced tables.

Sign up to request clarification or add additional context in comments.

Comments

1

Use SQL as much as possible. THis is the basic query, you could use. This is much more effecient than discarding the rows in PHP.

$query = "SELECT * FROM table_name WHERE p.id <> '$specific_id'" 

Comments

0

I think such as queries (like id based, or well indexed) must be on sql side... cause it uses indexes, and returns less data to your application. processing less data makes your applications runs faster.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.