PHP using arrays to reduce the time complexity of the program _php tutorial

Source: Internet
Author: User
Tags db2 pear
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.



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.

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:


$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); Gets the data from the database while ($row = $result->fetchrow (DB_FETCHMODE_ASSOC)) {//reads and displays the 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:


 $scorestr = "SELECT distinct SID from SCORES where course= ' Math ' and score>=90 '; $scoredata = $db 2ha Ndle->query ($SCORESTR); Gets the student number while ($score = $scoredata->fetchrow (DB_FETCHMODE_ASSOC)) that satisfies the condition from the database {//reads the student's number and finds 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); Displays the student's class echo "Classname=". $class [' CLASSNAME ']. " \ n ";} End and 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.



Main ideas: in the case where the required data is relatively simple and the data volume is stable, using the subscript (Index) of the PHP array can be used as a string (string) to subtly store the data temporarily 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 between CLASSID and CLASSNAME from the CLASSES table in a classarray one-dimensional array, and get the corresponding SID and STUDENTS and stuname from the CLASSID table The relationship is stored in the Stuarray 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:


$ClassArray = Array (), $StuArray = Array (), $classstr = "Select Classid,classname from CLASSES"; $classdata = $db 2handle-&gt ; query ($CLASSSTR); while ($class = $classdata->fetchrow (DB_FETCHMODE_ASSOC)) {//Generate Classarray Array, subscript index to ClassID name , 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 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 2h Andle->query ($SCORESTR); Gets the student number while ($score = $scoredata->fetchrow (DB_FETCHMODE_ASSOC)) that satisfies the condition from the database {//reads the student's number and reads the student's name from the Stuarray. Read class name echo "Studentname=" from Classarray. $StuArray [$score [' SID '] [' stuname ']. " \ t "; echo "Classname=".$ClassArray [$StuArray [$score [' SID '] [' CLASSID ']]. " \ n ";} End and 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:


 $ClassArray = Array (); $classstr = "Select Classid,classname from CLASSES"; $classdata = $db 2handle-& Gt;query ($CLASSSTR); while ($class = $classdata->fetchrow (DB_FETCHMODE_ASSOC)) {//Generate 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); Gets the student name and class number 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 and for getting each student ' s Info. Done 


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/320963.html www.bkjia.com true http://www.bkjia.com/PHPjc/320963.html techarticle 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, the application ...

  • 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.