performance.md 8.31 KB
Newer Older
1 2 3
Performance Tuning
==================

Larry Ullman committed
4
The performance of your web application is based upon two parts. First is the framework performance
5 6 7 8 9
and the second is the application itself. Yii has a pretty low performance impact
on your application out of the box and can be fine-tuned further for production
environment. As for the application, we'll provide some of the best practices
along with examples on how to apply them to Yii.

10 11 12 13 14 15 16 17 18 19
Preparing environment
---------------------

A well configured environment to run PHP application really matters. In order to get maximum performance:

- Always use latest stable PHP version. Each major release brings significant performance improvements and reduced
  memory usage.
- Use [APC](http://ru2.php.net/apc) for PHP 5.4 and less or [Opcache](http://php.net/opcache) for PHP 5.5 and more. It
  gives a very good performance boost.

20 21 22 23 24 25 26
Preparing framework for production
----------------------------------

### Disabling Debug Mode

First thing you should do before deploying your application to production environment
is to disable debug mode. A Yii application runs in debug mode if the constant
27 28 29 30 31 32 33 34 35 36
`YII_DEBUG` is defined as `true` in `index.php` so to disable debug the following
should be in your `index.php`:

```php
defined('YII_DEBUG') or define('YII_DEBUG', false);
```

Debug mode is very useful during development stage, but it would impact performance
because some components cause extra burden in debug mode. For example, the message
logger may record additional debug information for every message being logged.
37 38 39 40

### Enabling PHP opcode cache

Enabling the PHP opcode cache improves any PHP application performance and lowers
41 42 43 44
memory usage significantly. Yii is no exception. It was tested with both
[PHP 5.5 OPcache](http://php.net/manual/en/book.opcache.php) and
[APC PHP extension](http://php.net/manual/en/book.apc.php). Both cache
and optimize PHP intermediate code and avoid the time spent in parsing PHP
45 46 47 48 49 50 51 52 53 54
scripts for every incoming request.

### Turning on ActiveRecord database schema caching

If the application is using Active Record, we should turn on the schema caching
to save the time of parsing database schema. This can be done by setting the
`Connection::enableSchemaCache` property to be `true` via application configuration
`protected/config/main.php`:

```php
Alexander Makarov committed
55
return [
56
	// ...
Alexander Makarov committed
57
	'components' => [
58
		// ...
Alexander Makarov committed
59
		'db' => [
60 61 62 63 64 65 66 67 68 69 70
			'class' => 'yii\db\Connection',
			'dsn' => 'mysql:host=localhost;dbname=mydatabase',
			'username' => 'root',
			'password' => '',
			'enableSchemaCache' => true,

			// Duration of schema cache.
			// 'schemaCacheDuration' => 3600,

			// Name of the cache component used. Default is 'cache'.
			//'schemaCache' => 'cache',
Alexander Makarov committed
71 72
		],
		'cache' => [
73
			'class' => 'yii\caching\FileCache',
Alexander Makarov committed
74 75 76
		],
	],
];
77 78
```

79 80
Note that `cache` application component should be configured.

81 82
### Combining and Minimizing Assets

83 84 85 86
It is possible to combine and minimize assets, typically JavaScript and CSS, in order to slightly improve page load
time and therefore deliver better experience for end user of your application.

In order to learn how it can be achieved, refer to [assets](assets.md) guide section.
87 88 89

### Using better storage for sessions

90
By default PHP uses files to handle sessions. It is OK for development and
91 92 93 94 95
small projects but when it comes to handling concurrent requests it's better to
switch to another storage such as database. You can do so by configuring your
application via `protected/config/main.php`:

```php
Alexander Makarov committed
96
return [
97
	// ...
Alexander Makarov committed
98 99
	'components' => [
		'session' => [
100 101 102 103 104 105 106 107
			'class' => 'yii\web\DbSession',

			// Set the following if want to use DB component other than
			// default 'db'.
			// 'db' => 'mydb',

			// To override default session table set the following
			// 'sessionTable' => 'my_session',
Alexander Makarov committed
108 109 110
		],
	],
];
111 112
```

113
You can use `CacheSession` to store sessions using cache. Note that some
114
cache storage such as memcached has no guarantee that session data will not
115
be lost leading to unexpected logouts.
116

117 118
If you have [Redis](http://redis.io/) on your server, it's highly recommended as session storage.

119 120 121
Improving application
---------------------

122
### Using Serverside Caching Techniques
123 124 125 126 127 128 129 130 131 132

As described in the Caching section, Yii provides several caching solutions that
may improve the performance of a Web application significantly. If the generation
of some data takes long time, we can use the data caching approach to reduce the
data generation frequency; If a portion of page remains relatively static, we
can use the fragment caching approach to reduce its rendering frequency;
If a whole page remains relative static, we can use the page caching approach to
save the rendering cost for the whole page.


133
### Leveraging HTTP to save processing time and bandwidth
134

135 136 137 138 139
Leveraging HTTP caching saves both processing time, bandwidth and resources significantly. It can be implemented by
sending either `ETag` or `Last-Modified` header in your application response. If browser is implemented according to
HTTP specification (most browsers are), content will be fetched only if it is different from what it was prevously.

Forming proper headers is time consuming task so Yii provides a shortcut in form of controller filter
140
[[yii\web\HttpCache]]. Using it is very easy. In a controller you need to implement `behaviors` method like
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
the following:

```php
public function behaviors()
{
	return [
		'httpCache' => [
			'class' => \yii\web\HttpCache::className(),
			'only' => ['list'],
			'lastModified' => function ($action, $params) {
				$q = new Query();
				return strtotime($q->from('users')->max('updated_timestamp'));
			},
			// 'etagSeed' => function ($action, $params) {
				// return // generate etag seed here
			//}
		],
	];
}
```

In the code above one can use either `etagSeed` or `lastModified`. Implementing both isn't necessary. The goal is to
determine if content was modified in a way that is cheaper than fetching and rendering that content. `lastModified`
should return unix timestamp of the last content modification while `etagSeed` should return a string that is then
used to generate `ETag` header value.

167

168 169 170
### Database Optimization

Fetching data from database is often the main performance bottleneck in
171 172
a Web application.
Although using [caching](caching.md#Query-Caching) may alleviate the performance hit,
173 174 175 176 177 178 179 180 181 182
it does not fully solve the problem. When the database contains enormous data
and the cached data is invalid, fetching the latest data could be prohibitively
expensive without proper database and query design.

Design index wisely in a database. Indexing can make SELECT queries much faster,
but it may slow down INSERT, UPDATE or DELETE queries.

For complex queries, it is recommended to create a database view for it instead
of issuing the queries inside the PHP code and asking DBMS to parse them repetitively.

183
Do not overuse Active Record. Although Active Record is good at modeling data
184 185 186 187 188
in an OOP fashion, it actually degrades performance due to the fact that it needs
to create one or several objects to represent each row of query result. For data
intensive applications, using DAO or database APIs at lower level could be
a better choice.

189
Last but not least, use `LIMIT` in your `SELECT` queries. This avoids fetching
190 191 192 193
overwhelming data from database and exhausting the memory allocated to PHP.

### Using asArray

194 195 196 197
A good way to save memory and processing time on read-only pages is to use
ActiveRecord's `asArray` method.

```php
198 199 200 201 202
class PostController extends Controller
{
	public function actionIndex()
	{
		$posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all();
Alexander Makarov committed
203
		return $this->render('index', ['posts' => $posts]);
204 205
	}
}
206 207
```

208
In the view you should access fields of each individual record from `$posts` as array:
209 210

```php
resurtm committed
211
foreach ($posts as $post) {
212 213 214 215 216 217
	echo $post['title']."<br>";
}
```

Note that you can use array notation even if `asArray` wasn't specified and you're
working with AR objects.
218

219 220 221 222 223 224
### Processing data in background

In order to respond to user requests faster you can process heavy parts of the
request later if there's no need for immediate response.

- Cron jobs + console.
225 226
- queues + handlers.

227
TBD
228 229 230 231 232 233 234 235 236

### If nothing helps

If nothing helps, never assume what may fix performance problem. Always profile your code instead before changing
anything. The following tools may be helpful:

- [Yii debug toolbar and debugger](module-debug.md)
- [XDebug profiler](http://xdebug.org/docs/profiler)
- [XHProf](http://www.php.net/manual/en/book.xhprof.php)