PHP skillfully use arrays to reduce the time complexity of the program _php tutorial

Source: Internet
Author: User
Tags one table
About the author
Wang Dandan, a software engineer at IBM China Systems and Technology Center, has been working on WEB system design and development since 2006, and has five years of experience in designing and developing PHP applications.

Often developers write programs, often in the design or well-conceived operational logic, directly translated in the programming language. The program can be compiled smoothly, it is very gratifying. If the running time of the program is acceptable, you will be immersed in the sense of accomplishment of writing code, often ignoring the optimization of the code in this process. Only when the speed of the program is affected, you go back to thinking about optimizing things. This paper mainly introduces how to use arrays to reduce the time complexity caused by multi-layer loops in the programming of PHP. In particular, when a program needs to interact with the database multiple times, using this method to optimize your code will bring unexpected results.
What is the time complexity of the algorithm
Time complexity is a major factor used by developers to measure the merits of an application's algorithms. Objectively speaking, the advantages and disadvantages of the algorithm in addition to the complexity of time, but also closely related to spatial complexity. With the continuous improvement of hardware configuration, the space complexity of the algorithm is much looser for small and medium-sized applications. However, in today's Web2.0 era, there is a higher requirement for the time complexity of applications.
What is the time complexity of the algorithm? In summary, it refers to selecting an algorithm to represent the original operation, the number of times the original operation repeated execution as the algorithm time measurement. There are two factors that affect the time complexity: first, the execution time of the original operation and the number of executions caused by the original operation due to the control structure. In order to reduce the time complexity of the algorithm, it is easy to decrease the execution times of the original operation, and it is also the main method. The method described in this paper is to reduce the number of executions of the original operation by skillfully using an array of PHP, so as to achieve the need to reduce the complexity of the algorithm time, and share with you.
The time metric of the algorithm is denoted by T (n) =o (f (n)), which indicates that the number of times the basic operation of the algorithm is repeated is a function f (n) of the problem size n, which means that as the problem size n increases, the rate of execution time of the algorithm is the same as that of F (n). In most cases, we use the statement in the deepest loop as the original operation to discuss the time complexity of the algorithm, because it executes the same number of times as the statement that contains it. In general, it is only a matter of choosing a basic operation to discuss the time complexity of the algorithm. Sometimes it is also necessary to consider a variety of basic operations.
In web development, the execution time or response time of a function is usually not only related to the responsiveness and processing power of the server, but also to the interaction time of the third-party tools, such as the link time to the database and the time to access the data. Therefore, in the selection of the original operation, it is necessary to comprehensively consider the various aspects of the application, and to measure the time complexity of the algorithm by the operation which affects the execution time of the program. In other words, programmers need to have a basic understanding of the execution time of important operations when they write code.





Analysis of time complexity in common programs
Let us first look at an example, assuming that the development language of the WEB program is PHP, the background of the DB2 database, PHP through the PEAR::D b Data Abstraction layer to achieve access to the database.
Instance
The database has student table STUDENTS (see table 1), Class table CLASSES (see table 2), Student score table SCORES (see table 3), the need to display in the Web page of the test math scores more than 90 students name and the class.
Table 1. STUDENTS Table
Column Name
Describe
Sid
School Number
Stuname
Name
GENDER
Gender
Age
Age
CLASSID
Class number
...


Table 2. CLASSES Table
Column Name
Describe
CLASSID
Class number
CLASSNAME
Class name
...


Table 3. SCORES Table
Column Name
Describe
Sid
Students ' study number
COURSE
Subject
Score
Results
...




Depending on the individual programming habits, there are usually two approaches to solving this problem (the operation to access the database is expressed in PEAR::D b), see Methods 1, 2.
[Method 1] for STUDENTS, CLASSES, SCORES three tables to do a joint query, one time to obtain the student information and class information to meet the conditions. The PHP algorithm is described as follows:

Listing 1. Method 1
Copy CodeThe code is as follows:
$QUERYSTR = "SELECT distinct S.stuname as stuname,c.classname as CLASSNAME".
"From STUDENTS as s,classes as c,scores as R".
"Where S.sid=r.sid and S.classid=c.classid and r.course= ' Math '".
"and r.score>=90";
$result = $db 2handle->query ($QUERYSTR); Fetching data from the database
while ($row = $result->fetchrow (DB_FETCHMODE_ASSOC)) {
Reading and displaying data
echo "Studentname=". $row [' Stuname ']. " \ t classname= ". $row [' ClassName ']." \ n ";
}//done

[Method 2] Find the student number that satisfies the condition from the SCORES table, then find the student's name and class code from the STUDENTS table, and finally get the class name in the CLASSES table. The PHP algorithm is described as follows:

Listing 2. Method 2
Copy CodeThe code is as follows:
$SCORESTR = "SELECT distinct SID from SCORES where course= ' Math ' and score>=90 ';
$scoredata = $db 2handle->query ($SCORESTR);
Get the student number that meets the criteria from the database
while ($score = $scoredata->fetchrow (DB_FETCHMODE_ASSOC)) {
Read the student's number and find the student's name and class number in the students table
$studentstr = "Select Stuname,classid from STUDENTS where sid= '". $score [' SID ']. "'";
$studata = $db 2handle->query ($STUDENTSTR);
$stu = $studata->fetchrow (DB_FETCHMODE_ASSOC);
Show Student's name
echo "Studentname=". $stu [' Stuname ']. " \ t ";
Read the student's class number and find the student's class name in the classes table
$classstr = "Select CLASSNAME from CLASSES where classid= '". $stu [' CLASSID ']. "'";
$classdata = $db 2handle->query ($CLASSSTR);
$class = $classdata->fetchrow (DB_FETCHMODE_ASSOC);
Show student's class
echo "Classname=". $class [' CLASSNAME ']. " \ n ";
}//end while for getting each student ' s ID. Done

For such a description of the algorithm, I believe you will have a sense of déjà vu. This is also a widely used algorithm for most programmers. Because it has become accustomed to the thinking of the algorithmic logic directly into the code, and often do not have the time and mind to consider the merits of the algorithm. Here to analyze the time complexity of the two algorithms.
Because the Web server reads and displays data in a relatively small amount of time, generally in the order of 10ms, and the number of times to query and fetch data from the DB2 database is the order of magnitude of 100ms, and increases with the amount of data being queried. Therefore, the operation of querying the database can be used as the original operation to measure the complexity of time, in order to STUDENTS the amount of data in the table and the scores table as the problem size n (Generally, the data volume of the CLASSES table is small and relatively stable).
For Method 1, the number of accesses to the database is constant 1 as the problem size n increases. Thus, the time complexity is T (n) =o (1). For Method 2, assuming that the records in the SCORES table that meet the criteria have m, the original operation was executed as m+1. In other words, the number of executions of the original operation increases linearly with the increase of the data size n. The visible time complexity is t (n) =o (n). As can be seen, Method 1 has a low time complexity.
So where's the problem with method 1? Mainly because method 1 increases the database load, that is, the execution time of the original operation is greatly affected by the problem size n. Assume that the number of records for Students,classes,scores is X, Y, Z, respectively. Then, when performing a federated query operation, a matrix of x*y*z is formed in the database, then the number of records satisfying the condition is found in the matrix, and the Stuname information and classname of the records are obtained. This increases the number of records in the matrix table by increasing the data in any one table.


Using arrays to optimize algorithms
Main idea: In the case that the required data is relatively simple and the data volume is stable, using the subscript (Index) of the PHP array can be a string character, and the data is temporarily stored in the array. This makes it possible to quickly obtain the desired value by subscript (Index), thereby reducing the number of queries to the database, thus reducing the time complexity of the algorithm.
[Method 3] Get the correspondence of CLASSID and CLASSNAME from the classes table into a classarray one-dimensional array, get SID and students from the Stuname table, and CLASSID the corresponding relationship to Stuar Ray in a two-dimensional array. Then, from the scores table, find the student number that satisfies the condition, read the student's name and class number from the Stuarray array, and read the class name from the Classarray. The PHP algorithm is described as follows:

Listing 3. Method 3
Copy CodeThe code is as follows:
$ClassArray = Array ();
$StuArray = Array ();
$classstr = "Select Classid,classname from CLASSES";
$classdata = $db 2handle->query ($CLASSSTR);
while ($class = $classdata->fetchrow (DB_FETCHMODE_ASSOC)) {
Generate Classarray Array, subscript index is named ClassID, corresponding value is classname
$ClassArray [$class [' CLASSID ']] = $class [' CLASSNAME '];
}//end while $ClassArray
$stustr = "Select Sid,stuname,classid from STUDENTS";
$studata = $db 2handle->query ($STUSTR);
while ($stu = $studata->fetchrow (DB_FETCHMODE_ASSOC)) {
Generate Stuarray Array, subscript index is named SID, corresponding value is Stuname and ClassID
$StuArray [$stu [' SID ']][' stuname '] = $stu [' Stuname '];
$StuArray [$stu [' SID ']][' CLASSID '] = $stu [' CLASSID '];
}//end while $StuArray
$SCORESTR = "SELECT distinct SID from SCORES where course= ' Math ' and score>=90 ';
$scoredata = $db 2handle->query ($SCORESTR);
Get the student number that meets the criteria from the database
while ($score = $scoredata->fetchrow (DB_FETCHMODE_ASSOC)) {
Read the student's number and read the student's name from the Stuarray and read the class name from the Classarray.
echo "Studentname=". $StuArray [$score [' SID '] [' stuname ']. " \ t ";
echo "Classname=". $ClassArray [$StuArray [$score [' SID '] [' CLASSID ']]. " \ n ";
}//end while for getting each student ' s ID. Done

The time complexity of the improved method is still T (n) =o (1). Compared to Method 1, Method 3 does not have to worry about multiplying the cost of database queries due to increased records in a table. Compared with the method 2, the time complexity decreases, and the spatial complexity of the algorithm is not affected. Double benefit.
Although this optimization method is simple and easy to use, it does not mean that it is omnipotent. The issue of "degree" needs to be considered when using. Assuming that the data volume of the STUDENTS table is large, then the consumption of the system memory increases when the Stuarray is generated, and the spatial complexity of the algorithm is affected. In addition, when the amount of data is large enough, the main factors that affect the execution time of the algorithm are changed, and the original operation needs to be re-selected. In view of the large number of STUDENTS table records and the low and stable classes table records, it is possible to optimize the algorithm by combining nested query and array. The method 4 is given here for reference.
[Method 4] Gets the correspondence between CLASSID and CLASSNAME from the classes table into a classarray one-dimensional array. From the scores table, the students who meet the conditions of the student number, as Query STUDENTS table query criteria, to obtain students stuname and CLASSID. The name of the class is then read from the Classarray. The PHP algorithm is described as follows:

Listing 4. Method 4


Copy CodeThe code is as follows:
$ClassArray = Array ();
$classstr = "Select Classid,classname from CLASSES";
$classdata = $db 2handle->query ($CLASSSTR);
while ($class = $classdata->fetchrow (DB_FETCHMODE_ASSOC)) {
Generate Classarray Array, subscript index is named ClassID, corresponding value is classname
$ClassArray [$class [' CLASSID ']] = $class [' CLASSNAME '];
}//end while $ClassArray
$stustr = "Select Stuname,classid from STUDENTS where SID in".
"(select distinct SID from SCORES where course= ' M ' and score>=90)";
$studata = $db 2handle->query ($STUSTR);
Get student names and class numbers that meet the criteria from the database
while ($stu = $studata->fetchrow (DB_FETCHMODE_ASSOC)) {
Read the student's name and read the class name from the Classarray
echo "Studentname=". $stu [' Stuname ']. " \ t ";
echo "Classname=". $ClassArray [$stu [' CLASSID ']]. " \ n ";
}//end while for getting each student ' s Info. Done


Summarize
Methods 3 and 4 refer to arrays as a trick to subtly reduce the time complexity of the algorithm. In the actual application, the algorithm logic is much more complex, and the optimization of the algorithm needs to consider many factors synthetically. It should be suggested that the method described in this article applies not only to PHP applications. If the array of programming languages supports the use of strings as subscripts, the method proposed in this paper can be considered: using the subscript of array to reduce the time complexity of the algorithm. For programming languages that do not support string array subscripts, consider using a hash table to achieve the same effect.

http://www.bkjia.com/PHPjc/321045.html www.bkjia.com true http://www.bkjia.com/PHPjc/321045.html techarticle about the author Wang Dandan, IBM China System and Technology Center software engineer, since 2006 joined IBM, has been engaged in WEB system design and development work, has five years of PHP application design open ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.