When to use $sth->fetchrow_hashref, $sth->fetchrow_arrayref and $sth->fetchrow_array?

user380979 picture user380979 · Sep 9, 2010 · Viewed 20.6k times · Source

I know that:

  • $sth->fetchrow_hashref returns a hashref of the fetched row from database,
  • $sth->fetchrow_arrayref returns an arrayref of the fetched row from database, and
  • $sth->fetchrow_array returns an array of the fetched row from database.

But I want to know best practices about these. When should we use fetchrow_hashref and when should we use fetchrow_arrayref and when should we use fetchrow_array?

Answer

Ether picture Ether · Sep 9, 2010

When I wrote YAORM for $work, I benchmarked all of these in our environment (MySQL) and found that arrayref performed the same as array, and hashref was much slower. So I agree, it is best to use array* whenever possible; it helps to sugar your application to know which column names it is dealing with. Also the fewer columns you fetch the better, so avoid SELECT * statements as much as you can - go directly for SELECT <just the field I want>.

But this only applies to enterprise applications. If you are doing something that is not time-critical, go for whichever form presents the data in a format you can most easily work with. Remember, until you start refining your application, efficiency is what is fastest for the programmer, not for the machine. It takes many millions of executions of your application to start saving more time than you spent writing the code.