Home  >  Article  >  PHP Framework  >  Help you effectively improve ThinkPHP application performance!

Help you effectively improve ThinkPHP application performance!

藏色散人
藏色散人forward
2020-12-03 14:41:112781browse

The following is the thinkphp framework tutorial column to introduce to you how to effectively improve ThinkPHP Application performance, I hope it will be helpful to friends in need!

Help you effectively improve ThinkPHP application performance!

When it comes to application performance, there are too many aspects involved. There are many articles online about server optimization and front-end optimization, so I won’t go into details here. This article only briefly introduces some performance optimization methods and precautions that may be involved in ThinkPHP 5.1 application development (especially the deployment environment).

Recommendation: "ThinkPHP 5.1 World First Video Tutorial"

First of all, we must emphasize that the framework is not the bottleneck of application performance, architectural design, database and talents yes. At the beginning of the design of the framework, for the sake of versatility, it will not specifically perform in-depth optimization for a certain application, but it provides some possible means and configuration parameters for you to perform targeted tuning. Here are some possible optimization means. , which can be adjusted according to the situation during development.

The correct performance optimization steps should be: architecture optimization, database optimization, and code optimization.

1. Architecture optimization

Architecture optimization involves the selection and architecture of technology, storage, network, and services. Try to use mature and modern development architecture and design patterns. The front-end and back-end are designed to be completely separated, which facilitates independent optimization of the front-end and back-end, and makes testing easier.

If your application encounters a performance bottleneck, what you need to consider at this time is optimizing the architecture rather than optimizing the code itself, because the optimization effect at the architectural level is often the most significant.

2. Turn off debugging mode

Do not forget to turn off debugging mode in the deployment environment. This is not only for performance considerations, but also for security reasons. In fact, it is recommended to configure the debug mode to be turned off through environment variables, so that no configuration files need to be changed after deployment.

Because debugging mode affects logging information, additional debugging information and cache invalidation, turning off debugging mode can bring certain performance improvements.

3. Using a single module

Using the multi-module function will increase the I/O overhead of the file and additional configuration and checking. If it is not necessary when planning your application When designing the architecture, try to consider using a single module, and then use controller hierarchies to solve the problem of too many controllers.

The performance advantages of using a single module can be more fully reflected when deployed to swoole, because once the application file starts the service, it will be loaded into the memory, and the related files of the module It will be reloaded every time it is requested.

4. Routing design and optimization

When defining routing rules, do not use arrays, try to use methods to register routes, and use routing groups (or resource routing) more often. Group routing can reduce the number of route matches, thereby improving routing performance. If you have different routes for multiple domain names, you should also plan to use routes based on domain names.

Try to design operations such as data verification and permission checking of the current route in the routing. On the one hand, it is relatively clear. On the other hand, the verification operation can be carried out as early as possible without waiting for the controller to execute.

When there are many groups, enable delayed resolution of routes.

// 开启路由延迟解析
'url_lazy_route'    => true,

If there are many routing rules under the same group, it is recommended to merge the routing rules.

// 合并分组路由规则
'route_rule_merge'       => true,

For routing of GET requests, you can set the routing request cache.

// 定义GET请求路由规则 并设置3600秒的缓存
Route::get('new/:id','News/read')->cache(3600);

During the deployment phase, route caching can be enabled.

// 开启路由缓存(仅部署模式有效)
'route_check_cache'	=>	true,

5. Query optimization

First maintain good development habits and understand the correct usage posture of Db classes and models. For performance optimization of the database itself, you can refer to MySQL performance optimization The best 21 experiences, the following are mainly optimization strategies related to data query in the framework.

Reasonable use of query cache

Try to reduce the number of queries per request, and reasonably plan the data query cache for data queries that do not require high real-time performance (preferably use Redis cache).

Blog::where('id', 10)
    ->cache(30)
    ->find();

If you use related queries, the cache method can only be used for data caching of the main model, but you can use the remember method of the Cache class for convenient data caching.

$users = Cache::remember('users', function(){
    return User::with('profile')
        ->where('status', 1)
        ->select();},30);

Don’t be too obsessed with the number of queries

Trying to reduce the number of queries is for performance reasons, but it is not necessary. Using the fewest queries does not necessarily mean the highest performance. The performance of a complex JOIN query may not be as high as that of two simple queries, but using simple queries is clearer and easier to understand, and it is more convenient to cache data queries.

正确使用模型关联

不要总是以为模型的性能一定比Db类低,框架的ORM查询设计经过了较为合理的优化,正确使用模型一样可以有出色的性能,而且比Db查询要方便很多。

尤其是对于一些复杂的设计来说使用模型关联显得比直接用Db更加简单,例如使用关联预载入查询就可以避免N+1查询问题。

User::with(['profile','book'])->select();

如果用Db类自己实现的话,费时费力,性能还不一定优。

大量数据处理优化

对于大量数据的处理操作,使用chunk分批处理方法。

User::chunk(100, function($users) {
    foreach ($users as $user) {
        // 处理数据
    }});

对于内存开销比较大的应用,在做大量数据查询和处理的时候,使用cursor方法,可以利用PHP的生成器特性,减少内存占用。

$cursor = User::cursor();foreach($cursor as $user){
    // 处理数据
    }

你会发现用户数据不论是1万还是10万级别,内存开销并没有大的变化。

涉及到对大量数据的处理,包括数据迁移、批量更新,尽量使用命令行指令运行,否则会因为超时而中断。

善用数据集方法避免多次查询

可以通过数据集的方法完成的子集或者排序操作不要再次查询,例如:

// 模型查询返回数据集对象
$users = User::select();
// 按照用户的成绩由高到低排序
$list1 = $users->order('score', 'desc');
// 筛选成绩在90分以上的用户
$list2 = $users->where('score', '>=', 90);

字段缓存

利用下面指令在部署后生成字段缓存,可以减少每次数据表的字段查询开销。

php think optimize:schema

更多用法可以参考官方手册的数据字段缓存。

6.0 配置和公共文件缓存

每次在应用初始化或者模块初始化的时候会有一定的I/O开销,如果已经开启OpCache的话对性能影响甚微,如果比较在意的也可以通过命令行指令生成配置缓存(包括相关的公共文件和各种定义文件)。

生成应用配置缓存:

php think optimize:config

生成模块配置缓存:

php think optimize:config index

注意:一旦配置或者公共文件发生变化,必须重新生成。

7.0 生成类库映射

类库映射可以提升类库的自动加载性能,使用下面的指令可以生成系统类库和应用类库的类库映射(包括extend目录下的类库)。

php think optimize:autoload

vendor目录下的类库可以使用composer的dump-autoload指令优化加载性能。

composer dump-autoload -o

该命令把 PSR-0 和 PSR-4 转换为一个类映射表,来提高类的加载速度。

The above is the detailed content of Help you effectively improve ThinkPHP application performance!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete