23

I've read somewhere, and I don't remember where, that echo is a more efficient way of outputting data then print.

Why does Drupal core use print so much? Is there any special reason behind that?

3
  • 1
    On a sidenote: print will always return 1 as a value, echo won't return anything. I guess that might be useful in some cases.
    – Bart
    Commented Jun 21, 2011 at 14:26
  • What kind of case that might be?
    – jayarjo
    Commented Jun 21, 2011 at 17:38
  • I've wondered that too! Good question!
    – aendra
    Commented Jul 8, 2011 at 6:17

1 Answer 1

25

echo is only faster in academic environments. The difference is very marginal. A quick benchmark I just did: The time fetching one row from a table with more than 2000 nodes is 1 unit.

In order to get an improvement of 1 unit, I would need to replace about 3.700.000 (over 3 milion) print statements with echo. In other words, if you want performance improvements, this is hardly the place to start.

Seen that print can be used in a much wider range of cases then echo, the first has some advantages. It leaves you three options:

  • Always use print
  • Use echo where possible and fallback on print
  • Use echo always and refactor your code if echo cannot be used, to use it

Drupal has defaulted on the first.

To answer your actual question as to why this was chosen: It was not. It simply grew this way.

2
  • Could you provide an example of when echo cannot be used? It's just I can't imagine any at the moment.
    – jayarjo
    Commented Jun 21, 2011 at 17:41
  • 6
    The most obvious is if (! print some_method() ) {print some_other_method()}. Since print returns a TRUE if it actually printed something. Echo returns nothing, which is why it is faster too. Another example you will see is return print $somevalue at the end of a method to return the status.
    – berkes
    Commented Jun 27, 2011 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.