PHP skillfully use array to reduce the time complexity of the program _php skills

Source: Internet
Author: User
Tags db2 one table pear
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 experience in PHP application design and development.

Usually when developers write programs, they often translate the computational logic that has already been designed or conceived into the programming language directly. It is very pleasing that the program can be compiled smoothly. If the time of the program is still acceptable, you will be immersed in the sense of achievement of writing code, often in the process of ignoring the optimization of the code. It is only when the speed of the program is affected that you go back to thinking about optimization. This paper mainly introduces how to use arrays to reduce the time complexity caused by multi-layer loops in the programming of PHP. Especially when the 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 the main factor that developers use to measure the pros and cons of application algorithms. Objectively speaking, the advantages and disadvantages of the algorithm are related to the complexity of the time, but also to the complexity of space. With the continuous upgrading of hardware configuration, for small and medium sized applications, the space complexity of the algorithm requirements are also relaxed a lot. However, in today's Web2.0 era, the time complexity of the application has a higher demand.
What is the time complexity of the algorithm? In summary, it means to choose an algorithm to represent the original operation of the algorithm, the number of repeated execution of the original operation as the time measurement of the algorithm. There are two factors affecting time complexity: one is the execution time of the original operation and the other is the execution times caused by the control structure of the original operation. In order to reduce the time complexity of the algorithm, it is an easy way and the main method to decrease the execution times of the original operation. The method described in this paper is to use the PHP array, to reduce the number of execution times, so as to reduce the complexity of the algorithm time requirements, and share with you.
The time measurement of the algorithm is recorded as T (n) =o (f (n)), it indicates that the number of times the basic operation in the algorithm is repeated is a function f (n) of the problem scale n, which means that the growth rate of the algorithm execution time and the growth rate of f (n) are the same as the increase of the problem size n. In most cases, we discuss the time complexity of the algorithm as the original operation in the deepest loop, because it executes the same number of times as the statement that contains it. In general, the time complexity of the algorithm can only be discussed by selecting a basic operation for a problem. Sometimes you also need 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 time to link to the database and the time to access the data. Therefore, in the selection of the original operation is, the need to comprehensively consider the application of various factors, the maximum impact program execution time operation for the original operation, to measure the time complexity of the algorithm. 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's take a look at an example, assuming that the development language of the WEB program is PHP, the background of the DB2 database, PHP through PEAR::D b Data Abstraction layer to achieve access to the database.
Instance
The database contains student table STUDENTS (see table 1), Class table CLASSES (see table 2), Student score table SCORES (see table 3), the name and class of the students who have scored more than 90 on the math score in this exam will be displayed on the Web page.
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
Student study Number
COURSE
Subject
SCORE
Results
...




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

Listing 1. Method 1
Copy Code code 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); Getting data from the database
while ($row = $result->fetchrow (DB_FETCHMODE_ASSOC)) {
Reading and displaying data
echo "Studentname=". $row [' Stuname ']. " \ classname= ". $row [' ClassName ']." \ n ";
}//done

[Method 2] Find the student number that satisfies the condition from the SCORES table, then look for 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 Code code as follows:

$SCORESTR = "SELECT distinct SID from SCORES where course= ' Math ' and score>=90";
$scoredata = $db 2handle->query ($SCORESTR);
The student number from the database that satisfies the condition
while ($score = $scoredata->fetchrow (DB_FETCHMODE_ASSOC)) {
Read the student's school number and look up 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 to getting each student ' s ID. Done

For such an algorithm description, I believe that we will have déjà vu feeling. This is also a widely used algorithm for most programmers. Because has been accustomed to the thinking of the algorithm logic directly into the code, and often do not have the time and mind to consider the pros and cons of the algorithm. Here to analyze the time complexity of the two algorithms.
Because the Web server reads and displays data for a relatively small amount of time, typically in the order of magnitude 10ms, the order of magnitude of the time to query and get data from the DB2 database will be the order of magnitude 100ms, and increase with the amount of query data. Therefore, the query database operation can be used as a measure of time complexity of the original operation, to STUDENTS table and scores table data volume as the problem size n (usually, CLASSES table data volume is small and relatively stable).
For Method 1, the number of accesses to the database is constant 1 as the problem scale n increases. Thus, the complexity of Time is T (n) =o (1). For Method 2, assuming that the record that satisfies the condition in the SCORES table has m, the original operation is performed m+1. That is to say, with the increase of the data scale n, the execution times of the original operation increase linearly. The visible time complexity is t (n) =o (n). Thus, the time complexity of Method 1 is low.
So where is the problem with approach 1? Mainly because Method 1 will increase the database load, that is, the execution time of the original operation is affected by the problem scale N. Suppose the number of records in the 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 that satisfies the condition is found in the matrix, and the Stuname information and classname of the records are finally obtained. In this way, the increase in data in any one table results in the multiplication of records in the matrix table.


Using arrays to optimize algorithms
The main idea: in the required data in the case of relatively simple and stable data, the use of PHP array (Index) can be the character string (string), cleverly put the data into the array temporarily. In this way, the required values can be obtained quickly by subscript (Index), thus reducing the number of queries to the database, and thus reducing the time complexity of the algorithm.
[Method 3] The corresponding relationship of obtaining CLASSID and CLASSNAME from the classes table is deposited into the Classarray one-dimensional array, and the corresponding relationship between SID and students and stuname in the CLASSID table is stored to Stuar In a two-dimensional array of ray. Then find the student number that satisfies the condition from the scores table, 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 Code code as follows:

$ClassArray = Array ();
$StuArray = Array ();
$classstr = "Select Classid,classname from CLASSES";
$classdata = $db 2handle->query ($CLASSSTR);
while ($class = $classdata->fetchrow (DB_FETCHMODE_ASSOC)) {
Generates the Classarray array, the subscript index is named ClassID, and the 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)) {
Generates an array of Stuarray, the subscript index is named after the SID, and the 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);
The student number from the database that satisfies the condition
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 to 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 as a result of the increase in records in one table. Compared with Method 2, the time complexity decreases and the algorithm space complexity is not affected. Kill both birds.
Although this optimization method is simple and easy to use, it does not mean that it is omnipotent. You need to consider the "degree" problem when you use it. Assuming that the data volume of STUDENTS table is very large, then the consumption of the system memory is increased when generating stuarray, so the spatial complexity of the algorithm will be affected. In addition, when the data volume is large enough, the main factors that affect the execution time of the algorithm have changed, and the original operation needs to be selected again. In view of the STUDENTS table record number, the classes table record less and stable situation, we can consider the combination of nested query and array to optimize the algorithm. Method 4 is given here for reference.
[Method 4] obtains CLASSID and CLASSNAME correspondence from the classes table into the Classarray one-dimensional array. From the scores table, the student number of the students who meet the conditions is queried, and the STUDENTS table is queried to obtain the 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 Code code as follows:

$ClassArray = Array ();
$classstr = "Select Classid,classname from CLASSES";
$classdata = $db 2handle->query ($CLASSSTR);
while ($class = $classdata->fetchrow (DB_FETCHMODE_ASSOC)) {
Generates the Classarray array, the subscript index is named ClassID, and the 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 the student name and class number from the database that meet the criteria
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 to getting each student ' s Info. Done


Summarize
Method 3 and Method 4 refer to the small technique of array, which subtly reduces the time complexity of the algorithm. In the practical application, the algorithm logic is much more complicated, and the optimization of the algorithm needs to consider many factors. What you need to propose is that the methods described in this article apply not only to PHP applications. If the programming language array supports the use of strings as subscript, we can consider using the method proposed in this paper: skillfully using the subscript of the array to reduce the time complexity of the algorithm. For programming languages that do not support string arrays, consider creating a hash table to achieve the same effect.
Related Article

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.