PHP uses arrays to reduce the time complexity of programs.

Source: Internet
Author: User

About the author


Wang Dandan, software engineer of IBM China system and technology center, has been engaged in web system design and development since joining IBM in 2006. He has been using PHP for five years.ProgramExperience in design and development.

Original article:Http://www.ibm.com/developerworks/cn/opensource/os-cn-php-time/index.html

========================================================== ============================

November 26, 2009

When writing a program, developers usually directly use the designed or conceived computing LogicProgramming LanguageTranslate. It is a pleasure that the program can be compiled smoothly. If the running time of the program is acceptable at this time, the program will be immersed in writing.CodeIn this process, code optimization is often ignored. Optimization is taken into consideration only when the program running speed is affected. This article mainly introduces how to use arrays to reduce the time complexity caused by multi-layer loops in PHP programming. Especially when the program needs to interact with the database multiple times, using this method to optimize your code will bring unexpected results.

What isAlgorithmTime Complexity

Time complexity is the main factor that developers use to measure the merits and demerits of application algorithms. Objectively speaking, the advantages and disadvantages of algorithms are not only related to time complexity, but also closely related to space complexity. As the hardware configuration of devices continues to improve, the space complexity of algorithms is also relaxed for Small and Medium-sized applications. 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, programmers need to have a basic understanding of the execution time of important operations when writing code.

 



Back to Top

Analysis of time complexity in Common Programs

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.

Instance

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:


Listing 1. method 1


$ 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); // obtain data from the database
While ($ ROW = $ result-> fetchrow (db_fetchmode_assoc )){
// Read and display data
Echo "studentname =". $ row ['stdame']. "\ 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:


Listing 2. method 2

 
$ scorestr = "select distinct Sid from scores where course = 'Math' and score> = 90 ";
$ scoredata = $ db2handle-> query ($ scorestr );
// obtain qualified student ID from the database
while ($ score = $ scoredata-> fetchrow (db_fetchmode_assoc )) {
// read the student's student ID and search for the student's 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";
// Number of the student's class to be read, 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 student's 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 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.

 



Back to Top

Use arrays to optimize algorithms

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:


Listing 3. Method 3


$ 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. The subscript index is named as classid and 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 the student ID that meets the conditions from the database
While ($ score = $ scoredata-> fetchrow (db_fetchmode_assoc )){
// Read the student ID, the Student name from stuarray, and the class name from 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 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:


Listing 4. Method 4

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


Back to Top

Summary

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. If arrays in programming languages Support strings as subscript, we can consider using the method proposed in this article: The subscript of arrays can be used 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.