Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of output buffering?

I have read on many websites that using

ob_start(); 

can enhance your page load times, as it stores the php in a variable and displays it in one go rather than processing the php a bit of a time.

Also it is extremely useful for

header('location: /');

Some people say that this is spaghetti code, but as long as the code is clear and concise to any programmer then this should not be a problem, right?

What are your thoughts to using it, and what do you set as your output buffering, are there pros and cons to how, when and why I should or shouldn't use it.

like image 289
Version1 Avatar asked Apr 19 '11 11:04

Version1


People also ask

What is output buffer?

An output buffer is a location in memory or cache where data ready to be seen is held until the display device is ready. Buffer, Memory terms, Output.

What is output buffer php?

Output buffering is a mechanism for controlling how much output data (excluding headers and cookies) PHP should keep internally before pushing that data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify.


1 Answers

The main advantage of output buffering is that you can use it with the ob_gzhandler which will compress your output so you use less bandwidth. Good to use if your server is not setup to send php files compressed.

Another advantage is if your script uses a database or other constrained resources and you have some output before closing your connections or releasing those resources. Instead of having this kind of thing:

  1. Connect to database
  2. Start sending output to the user
  3. Wait for the user to receive everything
  4. Close the database connection

You have:

  1. Start buffering
  2. Connect to database
  3. Output some things
  4. Close database connection
  5. Send the buffer to the user.

When your script would need to be connected for 100ms to the database and your user need 300 more to download it, you can understand how output buffering can help releasing some stress on the database connections limit.

I know something coded well using a well configured server could nullify those advantages, but you never know who will code after you and you don't always have control of the server it's running on.

like image 103
Arkh Avatar answered Oct 04 '22 21:10

Arkh