PHP uses arrays to reduce program time complexity

Source: Internet
Author: User
Tags pear

As the hardware configuration of devices continues to improve Program For example Algorithm The requirements for space complexity are also quite relaxed. However, in today's web era, the time complexity of applications has higher requirements.

What is the time complexity of the algorithm? In summary, it refers to selecting an original operation that can represent the algorithm from the algorithm, and measuring the number of times the original operation is repeated as the algorithm's time. There are two factors that affect the time complexity: one is the execution time of the original operation, and the other is the number of executions of the original operation due to the control structure. It is easier to reduce the time complexity of the algorithm and reduce the number of original operations. The method described in this article is to use PHP arrays to reduce the execution times of the original operation and reduce the time complexity of the algorithm.

The algorithm's time measurement is recorded as T (n) = O (f (n )), it indicates that the number of repeated executions of the basic operation in the algorithm is a function f (n) of the problem scale N. That is to say, as the problem scale N increases, the algorithm execution time increases and F (N) the growth rate is the same. In most cases, we take the statements in the deepest loop as the original operation to discuss the time complexity of the algorithm, because the execution frequency is the same as the frequency of the statements containing it. Generally, you only need to select a basic operation for a problem to discuss the time complexity of the algorithm. Sometimes you also need to consider multiple basic operations at the same time.

In web development, the execution time or response time of a function is usually related not only to the server's response and processing capabilities, but also to the interaction time of third-party tools, for example, the connection time of the database and the access time of the data. Therefore, when selecting the original operation, you need to consider all aspects of the application, and take the operation that has the greatest impact on the execution time as the original operation to measure the time complexity of the algorithm. That is to say, the programmer needs to writeCodeYou can have a basic understanding of the execution time of important operations.


Let's take a look at an example. Assume that the development language of the web program is Php and the DB2 database is used in the background. php accesses the database through the pear: DB data abstraction layer.

The database contains students (see table 1), Class tables (see table 2), and student orders table scores (see table 3 ), the name and class of the student whose score exceeds 90 must be displayed on the web page.

Table 1. Students table

Column name Description
Sid Student ID
Stuname Name
Gender Gender
Age Age
Classid Class No.
...

Table 2. Classes table

Column name Description
Classid Class No.
Classname Class Name
...

Table 3. scores table

Column name Description
Sid Student ID
Course Subject
Score Score
...

There are usually two ways to solve this problem based on your programming habits (database access operations are represented by Pear: DB). For more information, see methods 1 and 2.

[Method 1]Perform a joint query on the students, classes, and scores tables to obtain the student information and class information that meet the conditions at one time. 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 = $ db2handle-> query ($ querystr); // get data from the database while ($ ROW = $ result-> fetchrow (db_fetchmode_assoc )) {// read and display the data echo "studentname = ". $ row ['stamp']. "\ t classname = ". $ row ['classname']. "\ n";} // done

[Method 2]Find the student ID that meets the conditions in the scores table, find the Student name and class code in the students table, and obtain 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 = $ db2handle-> query ($ scorestr); // obtain a qualified student ID from the database while ($ score = $ scoredata-> fetchrow (db_fetchmode_assoc )) {// read the student ID and find the Student name and class number in the students table $ studentstr = "select stuname, classid from students where Sid = '". $ score ['sid ']. "'"; $ studata = $ db2handle-> query ($ studentstr); $ Stu = $ studata-> fetchrow (db_fetchmode_assoc ); // display the Student name echo "studentname = ". $ STU ['stamp']. "\ t"; // read the student's class number and find the name of the student's class in the classes table $ classstr = "select classname from classes where classid = '". $ STU ['classid ']. "'"; $ classdata = $ db2handle-> query ($ classstr); $ class = $ classdata-> fetchrow (db_fetchmode_assoc ); // display the students' class echo "classname = ". $ class ['classname']. "\ n";} // end while for getting each student's ID. done 

I believe you will feel familiar with this algorithm. This is also an algorithm widely used by many programmers. Because we are used to directly translating the algorithm logic in our thinking into code, we often have no time or mind to consider the advantages and disadvantages of algorithms. Here we will analyze the time complexity of these two algorithms.

Because the time for the Web server to read and display data is relatively small, it is generally 10 ms, and the time for querying and obtaining data from the DB2 database is an order of magnitude of 100 ms, and the query data volume increases. Therefore, the database query operation can be used as the original operation to measure the time complexity, and the data volume in the students table and scores table is used as the problem scale N (generally, the data volume of the classes table is small and relatively stable ).

For method 1, as the problem scale N increases, the number of accesses to the database is constant 1. Therefore, the time complexity is T (n) = O (1 ). For method 2, if the scores table contains M records that meet the conditions, the number of original operations is m + 1. That is to say, as the data scale N increases, the number of original operations increases linearly. The time complexity is T (n) = O (n ). It can be seen that method 1 has a low time complexity.

So where is the problem with method 1? This is mainly because method 1 increases the database load, that is, the execution time of the original operation is greatly affected by the problem scale N. Assume that the number of students, classes, and scores records is X, Y, and Z respectively. When performing the joint query operation, a matrix of records x * y * z will be formed in the database, and then the number of records meeting the conditions will be queried in this matrix, finally, obtain the stuname information and classname of the record. In this way, increasing data in any table will multiply the number of records in the matrix table.


Main ideas:When the required data is relatively simple and the data volume is stable, the subscript (INDEX) of the PHP array (array) can be a string, cleverly store data in an array temporarily. In this way, you can quickly obtain the required value through the subscript (INDEX) to reduce the number of queries to the database, and thus reduce the time complexity of the algorithm.

[Method 3]Obtain the ing between classid and classname from the classes table and store it in the classarray one-dimensional array. Obtain the ing between sid, stuname, and classid from the students table and store it in the stuarray two-dimensional array. Then, find the student ID that meets the conditions in the scores table, read the Student name and class number from the stuarray, and read the class name from classarray. The PHP algorithm is described as follows:

$ Classarray = array (); $ stuarray = array (); $ classstr = "select classid, classname from classes"; $ classdata = $ db2handle-> query ($ classstr ); while ($ class = $ classdata-> fetchrow (db_fetchmode_assoc) {// generate a classarray array and name the index as classid, the corresponding value is classname $ classarray [$ class ['classid'] = $ class ['classname'];} // end while $ classarray $ stustr = "select Sid, stuname, classid from students "; $ studata = $ db2handle-> query ($ stustr); While ($ Stu = $ studata-> fetchrow (db_fetchmode_assoc )) {// generate the stuarray array. The subscript index is named by SID, the corresponding values are 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 = $ db2handle-> query ($ scorestr); // obtain a qualified student ID from the database while ($ score = $ scoredata-> fetchrow (db_fetchmode_assoc )) {// read the student's student ID, read the student's name from stuarray, and read the class name echo "studentname =" from classarray ". $ 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 T (n) = O (1 ). Compared with method 1, method 3 does not have to worry about the database query cost multiplied by the increase in the number of records in a table. Compared with method 2, the time complexity is reduced while the algorithm space complexity is not affected. You can give two birds a second.

Although this optimization method is easy to use, it does not mean that it is omnipotent. The "degree" must be considered during use. If the data volume of the Students table is large, the consumption of system memory increases when stuarray is generated, and the space complexity of the algorithm is affected. In addition, when the data size is large enough, the main factor affecting the algorithm execution time changes and the original operation needs to be re-selected. For scenarios where the number of students tables is large and the number of records in the classes table is small and stable, you can consider using a combination of nested queries and arrays to optimize the algorithm. Method 4 is provided for reference.

[Method 4]Obtain the ing between classid and classname from the classes table and store it in the classarray one-dimensional array. The student ID that meets the conditions is queried from the scores table as the query condition for the students table to obtain the student's stuname and classid. Then read the class name from classarray. The PHP algorithm is described as follows:

 $ classarray = array (); $ classstr = "select classid, classname from classes "; $ classdata = $ db2handle-> query ($ classstr); While ($ class = $ classdata-> fetchrow (db_fetchmode_assoc) {// generates a classarray array. The subscript index is named by classid, 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 = $ db2handle-> query ($ stustr ); // obtain the qualified student name and class number from the database while ($ Stu = $ studata-> fetchrow (db_fetchmode_assoc) {// read the Student name, and read the class name echo "studentname =" from classarray ". $ STU ['stamp']. "\ t"; echo "classname = ". $ classarray [$ STU ['classid ']. "\ n";} // end while for getting each student's info. done 

The array technique is referenced in Methods 3 and 4, which cleverly reduces the time complexity of the algorithm. In practical applications, the algorithm logic is much more complex, and many factors need to be taken into account for algorithm optimization. The method described in this article is not only applicable to PHP applications. IfProgramming LanguageThe method proposed in this article is to use the subscript of the array to reduce the time complexity of the algorithm. For programming languages that do not support strings as the underlying targets of arrays, you can consider using hash tables to achieve the same effect.

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.