To implement the best possible solutions, we typically prepare a roadmap. This roadmap consists of easiest to most labor-intensive steps to help us optimize our applications and our time.
One simple and quick solution is to upgrade our servers and make use of more memory, CPU, etc. Alas, this route has considerable drawbacks, such as cost. However, there are other ways to achieve faster speeds in your applications and in this blog post, I’d like to share with you some tips that I’ve gained through my personal experience working with Yii2 applications.
My first tip is to conduct a small test using the Apache HTTP Server Benchmarking Tool. Here is an example:
ab -n 100 -c 10 http://<your domain>/
In this example, we get poor results:
1Requests per second: 4.39 [#/sec] (mean)
2Time per request: 228.039 [ms] (mean, across all concurrent requests)
Using a few small tweaks, we can speed up the work:
- Update the framework, php, and mysql to the latest versions.
Please note that this is only a recommendation. Unfortunately, it is not always possible to do this in real life projects. Nevertheless, using the newest versions can be much better in the long run and can resolve problems with speed, security, as well as add extra features. However, it should also be noted that updating versions should be very attentive. New versions can break existing features due to some points getting deprecated and deleted.
- Check project environments and turn everything on in production mode. Furthermore, disable debugging mode on the production server.
1defined('YII_DEBUG') or define('YII_DEBUG', false);
2defined('YII_ENV') or define('YII_ENV', 'prod');
- Add quick configuration changes.
- Add caching
Yii2 framework supports a lot of cache methods, some examples are:
1yii\caching\ApcCache
2yii\caching\DbCache
3yii\caching\FileCache
4yii\caching\MemCache
5yii\redis\Cache
FileCache being the simplest, it is also the least optimal one. Nonetheless, even it will help in optimizing your project. Decide what’s best for your needs.
- Add in your config file:
1return [
2 'components' => [
3 'cache' => [
4 'class' => 'yii\caching\FileCache',
5 ],
6 ],
7];
- Enable database connection cache
- Add in your config file:
1return [
2 'components' => [
3 'db' => [
4 'class' => 'yii\db\Connection',
5 'dsn' => 'mysql:host=localhost;dbname=mydatabase',
6 'username' => 'root',
7 'password' => '',
8 'enableSchemaCache' => true,
9 'schemaCacheDuration' => 3600,
10 'schemaCache' => 'cache',
11 ],
12 ],
13];
- Use a session storage, such as Redis server. Working with files is always slower than working with RAM.
- Add in your config file:
1return [
2 'components' => [
3 'session' => [
4 'class' => 'yii\redis\Session',
5 'redis' => [
6 'hostname' => 'localhost',
7 'port' => 6379,
8 'database' => 0,
9 ]
10 ],
11 ],
12];
- Enable page cache
1class DefaultController extends Controller
2{
3 ...
4 public function filters()
5 {
6 return [
7 [
8 'COutputCache',
9 'duration' => 60,
10 'varyByParam' => ['id'],
11 ],
12 ];
13 }
14}
- Add static file resources optimization.
The easiest way to do this is to enable nginx static file cache on the server side. This change can help with server connections and allows static files to be used in browser cache.
1location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
2 expires max;
3}
4
5location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm)$ {
6 expires 1M;
7 access_log off;
8 add_header Cache-Control "public";
9}
- Enable text compression on the server side. This additional setting can reduce the request content size.
1server {
2 ...
3 gzip on;
4 gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
5 ...
6}
- Add component loader optimization.
composer dumpautoload -o
Once these tweaks have been implemented, we should be able to see some significant improvements:
1Requests per second: 22.74 [#/sec] (mean)
2Time per request: 43.982 [ms] (mean, across all concurrent requests)
These are some of the quickest and easiest steps we can take to optimize our applications. Once these things have been implemented and/or reviewed, we can further optimize our applications by resolving bad solutions in code. This can take more time, resources and can be done in multiple different ways. Here are a few things to look into:
Database
Working with the database, we can use MySQL. If you’ve upgraded to the latest version, you can work with queries.
- Optimize slow queries using MySQL Slow Query Log
1log_slow_queries = 1;
2slow_query_log_file = <some file name>;
- Remove duplicate queries (can be searched using Yii2 debugger)
1[
2'bootstrap' => ['debug'],
3'modules' => [
4 'debug' => [
5 'class' => 'yii\debug\Module',
6 ],
7]
8
9]
- Use cache on the most used queries
1$result = $db->cache(function ($db) {
2
3 // SQL queries that use query caching
4
5 // do not use query caching for this command
6 $customer = $db->createCommand('SELECT * FROM customer WHERE id=1')->noCache()->queryOne();
7
8 // ...
9
10 return $result;
11});
- Remove from the queries a selection of data that is not used
This:
1SELECT id, column1, column2 ..
2FROM table_name
is better than this:
1SELECT *
2FROM table_name
- Normalize / Denormalize tables
- Add table columns indexes
Remote services
Working with remote services can add many problems. If it’s possible, break away from remote services. You can also prepare and save data from remote services using background workers, queues or cron jobs. This should resolve problems when remote services are broken or have incorrect work.
Work with resources
- Use cdn servers for css/js libraries
- Use of minified libraries. Most libraries have min versions; this should be better than full versions on production mode.
- For custom scripts / styles, you can combine and minify.
Project code
You can use php xhprof extension; this extension can help with dirty code and fix bottlenecks.
Work With Server Configuration and Refactoring Structure
There is not one perfect solution for this and all possible solutions should be analyzed and worked on individually.
There are numerous ways to optimize application speed and you should look into each possible solution. It is always better to use optimal solutions from the get-go in order to save yourself and your client a headache. The tips I’ve shared in this blog post are not all possible solutions and there may be other options you may want to explore to find what’s best for your needs.
Accelerate Your Career with 2am.tech
Join our team and collaborate with top tech professionals on cutting-edge projects, shaping the future of software development with your creativity and expertise.
Open Positions