search
HomeBackend DevelopmentPHP Tutorial追求程序速度,而不是编程的速度_php技巧

        1.使用内嵌的HTML代码,而不是PHP的echo语句。
因为PHP是一门嵌入式Web编程语言,可以将HTML代码和PHP代码相互嵌入。但是很多程序员担心在HTML代码中过多的使用""嵌入PHP代码会多次调用PHP解释器,从而降低了PHP代码的运行速度,所以宁愿使用PHP的echo语句来输出HTML代码,而不直接使用HTML代码。但事实却恰恰相反。每一个PHP页面只调用一次PHP解释器来解释所有的PHP代码,所以,只在需要时才嵌入PHP代码,而大多数的时候直接使用HTML代码输入结果,不但不会降低程序的运行速度,而且因为减少了对echo语句的解析,往往可以提高代码的运行速度。
下面的一段代码证明了我们的结论。在这段代码中,我们使用了前面介绍的时间测试函数。 

      2.使用str-replace而不是ereg-replace
       习惯使用Perl进行编程的程序员更加愿意使用ereg_replace完成字符串替换工作,因为在PHP中ereg_replace的用法和Perl中模式匹配的用法相近。但是,下面的这段代码证明,使用str_replace 代替 ereg_replace将可以大大提高代码的运行速度。

测试str_replace和ereg_replace的运行速度

//这段代码测试str_replace的运行速度


emphasis; ?>

for ($i=0; $istr_replace(i>, b>, $string).

}
?>

//这段代码测试ereg_replace的运行速度

for ($i=0; $iereg_replace(, , $string).

}
?>

//打印结果

结论

使用str_replace的时间 -

使用ereg_pattern的时间 -
运行上面的代码,得到的结果是:
使用str_replace的时间 - 0.089757
使用ereg_pattern的时间 - 0.248881
从运行的结果我们可以看出使用str_replace替代ereg_replace作为字符串替换函数,极大地提高了代码的运行速度。


        3.注意字符串的引用
        PHP和其它很多编程语言一样,可以使用双引号("")来引用字符串,也可以使用单引号()。但是在PHP中,如果使用双引号来引用字符串,那么PHP解析器将首先分析字符串中有没有对变量的引用,有变量的话,将对变量进行替换。如果是单引号,则没有如此复杂——直接将单引号包含起来的所有字符串直接显示出来。显然,在PHP编程中,如果使用单引号引用字符串变量要比使用双引号快速一些。


        4.在数据库中避免使用联合操作
        比起其它的Web编程语言来说,PHP的数据库功能十分强大。但是在PHP中数据库的运行仍然是一件十分费时费力的事情,所以,作为一个Web程序员,要尽量减少数据库的查询操作,同时应该为数据库建立适当的索引。另一件值得注意的事情是在用PHP操作数据库时,尽可能不使用多个数据表的联合操作,尽管联合操作可以增强数据库的查询功能,但是却大大增加了服务器的负担。
为了说明这个问题,我们可以看看下面的这个简单的例子。


我们在数据库中创建了两个数据表foo和big_foo。在数据表foo中,只有一个字段,包含了从1-1000之间的所有自然数。数据表big_foo同样只有一个字段,但包含了从1-1,000,000之间的全部自然数。所以,从大小上说,big_foo等于foo与它自身进行了联合操作。
$db->query("select * from foo");
0.032273 secs
$db->next_record();
0.00048999999999999 secs
$db->query("insert into foo values (NULL)");
0.019506 secs
$db->query("select * from foo as a, foo as b");
17.280596 secs
$db->query("select * from foo as a, foo as b where a.id > b.id");
14.645251 secs
$db->query("select * from foo as a, foo as b where a.id = b.id");
0.041269 secs
$db->query("select * from big_foo");
25.393672 secs
从上面操作结果我们可以发现,对于两个有1000条记录的数据表进行联合,其速度并不比对一个1000000条纪录的大型数据表单独进行操作快多少。


         5.注意include与require的区别
        在PHP变成中,include()与require()的功能相同,但在用法上却有一些不同,include()是有条件包含函数,而require()则是无条件包含函数。例如在下面的一个例子中,如果变量$somgthing为真,则将包含文件somefile:
if($something){
include("somefile");
}
但不管$something取何值,下面的代码将把文件somefile包含进文件里:
if($something){
require("somefile");
}
下面的这个有趣的例子充分说明了这两个函数之间的不同。
$i = 1;
while ($i require("somefile.$i");
$i++;
}
在这段代码中,每一次循环的时候,程序都将把同一个文件包含进去。很显然这不是程序员的初衷,从代码中我们可以看出这段代码希望在每次循环时,将不同的文件包含进来。如果要完成这个功能,必须求助函数

include(){
$i = 1;
while ($i include("somefile.$i");
$i++;
}


        6.注意echo和print的区别
        PHP中echo和print的功能也基本相同,但是两者之间也有细微差别。在PHP代码中可以把print作为一个普通函数来使用,例如执行下面的代码后变量$res的值将为1。
$ret = print "Hello World";
这意味着print可用在一些复杂的表达式中,而echo则不行。同样,在代码中echo语句的运行速度要略微快于print语句,因为echo语句不要求返回任何数值. 
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment