Which is better to format a date, PHP or in the MySQL query? would having MySQL format the date lower performance?

    It's a good question. I don't know the answer but it should be pretty easy to test.

    I'll bet 50 cents that letting MySQL do it is going to be about .01% faster. Small enough that it doesn't matter.

    Write a script that does this

    1. open a scratch file for writing
    2. $start = the current time
    3. select a million records from a database and formats the date
      (can't be the same record a million times because the query result is cached)
    4. write each to the scratch file (do not print to screen)
    5. $duration = the current time - $start

    Run it a few times to see if the times are consistent

    Then similarly, write a script that does this:

    1. open a scratch file for writing
    2. $start = the current time
    3. select a million records from a database but does not format the date
    4. format the date in PHP
    5. write each to the scratch file (do not print to screen)
    6. $duration = the current time - $start

    While this might be too crude a test for some purposes, it will be good enough to determine if one is vastly slower than the other.... but I suspect that they're going to be almost equal.

      I normally do it in the SQL query, because in PHP you would have to use multiple functions to first convert the date into a Unix timestamp and then format the timestamp into whatever you'd like.

        Write a Reply...