BigJ
BigJ

Reputation: 2032

Faster: Iterate list or JPQL query?

What would be faster to find a match: iterate over a list, or perform a JPQL query? On average of course, because this also depends on where the match is in the list. Would the answer depend on the list size?

Example: find the Person with name "Joe" (unique name)

JPQL:

TypedQuery<Person> q = em.createQuery(  "SELECT p " +
                                        "FROM Person p " +
                                        "WHERE p.name = :name ", Person.class);
q.setParameter("name", "Joe");
return q.getResultList().size() == 1;

Iterate:

for (Person p : persons) {
    if ("Joe".equals(p.name)) {
        return true;
    }
}
return false;

Upvotes: 1

Views: 767

Answers (1)

Windle
Windle

Reputation: 1392

Whether the finding the specific person will be faster in Java or the DB is really dependent on your specific situation and if you're having problems with performance here, you should really just time both implementations.

There are a bunch of things to consider. A big one is, where does persons come from in your iteration example? Do you already have a list of people on hand, or do you have to SELECT all the people out of the db right before that? If you are going to query the Person table anyway, you're probably better off just throwing that simple where clause on.

Also, the number of results may matter if there are a lot. If you only have 5 people in your db then any difference in implementation speed will probably be so small you won't notice. If you have a couple million then those differences will be amplified.

My gut feeling is that it probably doesn't make a significant difference either way for your case and you should use whichever you are more comfortable with. If this is really a performance bottleneck though, then you need to time them both before you start worrying about fiddling with tables, indexes, threading, whatever.

Upvotes: 2

Related Questions