Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 一个php数据库插入记录的性能对比产生的问题。

一个php数据库插入记录的性能对比产生的问题。

Jun 23, 2016 pm 01:27 PM

我是搞C#的,最近因为一些原因吧,也在学点php。
今天测试了一段代码,很简单,就是往数据库里写入一行记录。抓一下这段程序的执行时间,产生了一个疑问:php怎么这么慢。

我的php环境是phpstudy集成环境,php版本是5.3.29,服务器用的nginx。
mysql数据库有张表users:
id(自增列),name(varchar),time(time)
我php的测试代码:

<script>function r(s){	window.location=s;}</script><?php$starttime = explode(' ',microtime());$p = Request("p");if($p==""){	InsertRecord(getRand());	echo "插入第1条记录。";	echo "<script>setTimeout(\"r('?p=2');\",10)</script>";}else{	$q = (int)$p;	InsertRecord(getRand());	echo "插入第".$q."条记录。";	echo "<script>setTimeout(\"r('?p=".($q+1)."');\",10)</script>";}$endtime = explode(' ',microtime());$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);$thistime = round($thistime,3);echo "<br>本网页执行耗时:".$thistime." 秒。".time();function Request($s){	if($_REQUEST)	{		$p = $_REQUEST[$s];		if($p == "")		{			return "";		}		else		{			return $p;		}	}	else		return "";}function getRand(){	$a = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_()&^}{+=|?!@#$%";	$start = rand(0,strlen($a)-1);	$len = rand(1,strlen($a));	$str = substr($a,$start,$len);	echo "生成的用户名:" . $str ."<br>";	return $str;}function InsertRecord($s){	$link = mysql_connect('localhost', 'root', 'root');	if (!$link) {		die('Could not connect: ' . mysql_error());	}	//echo 'Connected successfully';			$sql = "insert into users (name,time) values ('" . $s . "','" .date('y-m-d h:i:s',time())."')";	// 执行sql查询	mysql_select_db("test", $link);//设定要操作的数据库	//$result=mysql_query($sql, $link);	if (!mysql_query($sql,$link))	{		die('Error: ' . mysql_error());	}	mysql_close($link);	//echo "1 record added";	}?>
Copy after login


我发现执行时间居然有1秒多点,发现很慢。

而相同的,我用C#整了段代码:
        protected void Page_Load(object sender, EventArgs e)        {            DateTime start = DateTime.Now;            Run();             DateTime end = DateTime.Now;            TimeSpan span = end - start;            double seconds = span.TotalSeconds;            Response.Write("程序耗时:" + seconds);        }        private static void Run()        {            string name = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRS";            Console.WriteLine("插入:" + name);            MySqlConnection conn = new MySqlConnection();            conn.ConnectionString = "server=localhost;User Id=root;password=root;Database=test";            conn.Open();            MySqlCommand cmd = new MySqlCommand();            cmd.Connection = conn;            cmd.CommandText = "insert into users (name,time) values ('" + name + "','" + DateTime.Now.ToString() + "')";            cmd.ExecuteNonQuery();            cmd.Dispose();            conn.Close();            conn.Dispose();        }
Copy after login

结果是速度远超php了。
测试结果:



对比差别能这么大吗?


回复讨论(解决方案)

测试用的机器是同一台,配置为win7,i3,5400转硬盘

测试一次,不能说明任何问题



测试当然不是一次呢,可以看到,php代码里用了个循环,我监测了5000多次的写入,每次的写入都是处于1秒左右的。

而同样的,c#的,持续的几十次,除第一次大约是在0.15秒左右外,其他的都是在0.0001秒左右。

所以不是一次的,我是想问问为什么会这样,是代码有问题还是测试环境有问题。

您的循环是 http 大循环,测试的实际是整个 web 系统的响应速度
至少还需要一组无数据库访问页面做对照

多换几个机器测试,综合对比下

注释掉数据库执行后的结果:执行时间都是一样,几乎为0.






是否能从这说明就是php的性能问题?是因为win 7的原因吗?

注释掉数据库执行后的结果:执行时间都是一样,几乎为0.






是否能从这说明就是php的性能问题?是因为win 7的原因吗?



把代码改一下

php -q  测试文件.php

直接跑看结果

结果一样,还是要1秒

慢点很正常,逻辑清晰就好。解释和编译如何对比!!

慢点很正常,逻辑清晰就好。解释和编译如何对比!!



那是否是说两者的性能差异是因为一个编译了一个是脚本解释执行的?

但就算是这样,差异不会这么大吧。

难道说PHP已经衰落了么。。。。。。

难道说PHP已经衰落了么。。。。。。



别在那开玩笑,我相信现在这么大的互联网企业用php开发高并发应用,说明php的性能其实是很可观的。

我是想搞明白为什么我测试的却是这样,是代码问题还是环境问题。

无论如何,插入一条记录是不可能要花费 1 秒的
测试时,对照组要有对等的条件
Mysql.net 只在第一次连接数据库时存在真实的物理连接操作,这与 php mysql 扩展的长连接是等效的
但你测试时,php 用的是短连接
我前面已经说了,你测试的是整个 http 会话的时间。下结论前应刨去非 MySQL 的因素

nginx + php 是 CGI 工作方式
你也没说明 C# 是什么方式工作的

如果你把运行环境造成的延时都归罪于 MySQL 的话,显然是不公正的

很明显嘛 

把localhost换成127.0.0.1,因为MySQL会去走一个DNS解析的过程,在服务器上也应该使用ip来进行数据库连接,或者在(windows)my.ini里面修改一下配置也是可以的。

就算(当前)测试整个http的周期PHP都还是强过.net的.

C#是直接使用VS2010自带的asp.net Development server调试的,没有附加的内容。
前边尝试过去掉数据库执行的代码,同样再运行,耗时和C#里一样,都是0(或是约等于0)
而加上数据库执行代码后,一个就是1秒多,一个就是0.001秒,那这样应该是可以判断问题出在访问mysql的环节吧。

php访问mysql数据库是自带的驱动吗?C#是直接从官网下载的连接库。

很明显嘛 

把localhost换成127.0.0.1,因为MySQL会去走一个DNS解析的过程,在服务器上也应该使用ip来进行数据库连接,或者在(windows)my.ini里面修改一下配置也是可以的。

就算(当前)测试整个http的周期PHP都还是强过.net的.



这个不符合逻辑吧,就算要走dns解析,总不会php走,c#就不走了吧,我那里都用的localhost,并没有哪里使用的ip。

整http周期,php都强过.net,这个似乎跟我这个测试有冲突吧。

或许如同xuzuning所说,是我测试方法不正确,但粗略来看,这个似乎也并不大的不妥吧,我所知道的是现在很多大型网站都是使用nginx作为php的容器在使用,而我测试C#的只是使用的VS2010自带的测试服务器,这两者之间本身是存在差异的吧。

这个不符合逻辑吧,就算要走dns解析,总不会php走,c#就不走了吧,我那里都用的localhost,并没有哪里使用的ip。

我并没有不允许你把PHP和.NET都使用127.0.0.1去访问。

你发问题讨论的内容是: 在同等的机器下,使用 "合理" 的方法得到 "合理" 的结果。

或许如同xuzuning所说,是我测试方法不正确,但粗略来看,这个似乎也并不大的不妥吧,我所知道的是现在很多大型网站都是使用nginx作为php的容器在使用,而我测试C#的只是使用的VS2010自带的测试服务器,这两者之间本身是存在差异的吧。 

你不觉得是跑偏了?


这个不符合逻辑吧,就算要走dns解析,总不会php走,c#就不走了吧,我那里都用的localhost,并没有哪里使用的ip。

我并没有不允许你把PHP和.NET都使用127.0.0.1去访问。

你发问题讨论的内容是: 在同等的机器下,使用 "合理" 的方法得到 "合理" 的结果。

或许如同xuzuning所说,是我测试方法不正确,但粗略来看,这个似乎也并不大的不妥吧,我所知道的是现在很多大型网站都是使用nginx作为php的容器在使用,而我测试C#的只是使用的VS2010自带的测试服务器,这两者之间本身是存在差异的吧。 

你不觉得是跑偏了?



恐怕是你这里理解错了,我的问题是同一台机器,不同的服务器环境,性能差别为什么这么大?大的原因是代码问题还是环境问题,还是测试方法的问题,我说到的那些使用nginx作为容器,这怎么就是跑偏了?

开发php应用程序,不要在windows的框架上折腾,操作系统请换成linux,lamp架构!!!
这样的php性能是最好的。

开发php应用程序,不要在windows的框架上折腾,操作系统请换成linux,lamp架构!!!
这样的php性能是最好的。



我还没入门,只是在学的阶段,windows环境下的环境是最容易布署的。

我让你改代码 希望你改成 单纯的插入数据这样来测试.其次一个呢 我们暂时没你那样的环境做测试 所以也得不出其他结果 兴许你换一台电脑就跑出不一样的结果了,彼此的数据库驱动应该都不是一样的吧 C#是不是有自己的数据库驱动呢.

最后呢 要用mysqli 来测试.....mysql 已经淘汰了.

我让你改代码 希望你改成 单纯的插入数据这样来测试.其次一个呢 我们暂时没你那样的环境做测试 所以也得不出其他结果 兴许你换一台电脑就跑出不一样的结果了,彼此的数据库驱动应该都不是一样的吧 C#是不是有自己的数据库驱动呢.

最后呢 要用mysqli 来测试.....mysql 已经淘汰了.



试了把mysqli,结果是一样的,没有变化。

算了,结贴,也许php不是想象中的那么强大。

楼主真逗,写了一段这样的代码就来对比性能

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

See all articles