简体   繁体   English

哪一个更快,为什么?-函数内部和外部的php连接

[英]Which one is faster and why - Php connection inside and outside of the function

I am working on a PHP project I found there are two ways to make database connections one is from inside of a function and another one is from outside of the function. 我在一个PHP项目上工作,发现有两种建立数据库连接的方法,一种是从函数内部进行,另一种是从函数外部进行。 as follows. 如下。

<?php
function_connect1();
function_connect2();
?>

The function_connect1 and 2 is in a separate file called functions.php its as follows.in at this snippet I am making connection each time the function is being called. function_connect1和2在一个名为functions.php的单独文件中,如下所示。在此代码段中,每次调用该函数时,我都进行连接。

<?php
//Function connect1
    function function_connect1(){
    $db_vars=(VARS);
    $connection=mysqli_connect($db_vars);
    //Functions objectives
    mysqli_close($connection);
    }
//Function connect2
    function function_connect2(){
    $db_vars=(VARS);
    $connection=mysqli_connect($db_vars);
    //Functions objectives
    mysqli_close($connection);
    }
    ?>

The above snippet can be written in at the following way as well open a db connection first time and close the same connection after all the functions are being excicuted. 可以按以下方式编写上面的代码段,以及在所有功能都被删除后,第一次打开db连接并关闭同一连接。

<?php
$db_vars=(VARS);
$connection=mysqli_connect($db_vars);
function_connect1();
function_connect2();
mysqli_close($connection);
?>

Can anybody can tell me which one is fast and why. 谁能告诉我哪一个速度快,为什么。

If you want to make more queries to the database server, it is advisable (and faster) to open the connection, run queries and close it after all work is done. 如果要对数据库服务器进行更多查询,建议(并且更快)打开连接,运行查询并在完成所有工作后将其关闭。 Closing and re-opening the connection for each query will be always slower. 关闭和重新打开每个查询的连接总是比较慢。

1 connection takes X time. 1个连接需要X的时间。
2 connections take 2X time. 2个连接花费2倍的时间。
10 connections take 10X time. 10个连接需要10倍的时间。

now you can figure it out yourself 现在你可以自己弄清楚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM