search
HomeDatabaseMysql Tutorial读写文件与读写数据库的效率比较_MySQL

bitsCN.com

这个问题也是最近才想到的,就是到底读文件更快还是读数据库更快,能快多少,天缘也搜索过,没见有网友就这个问题答复过,也可能是太简单的缘故,我们本文还是来实测一下,由于时间关系,VC还没装,天缘先用PHP测试了一下,下次有时间在C/C++上补充测试到本文来,因为PHP的底层解析应该也是基于C的,所以估计两者环境测试结果差不多,小问题大收获,现在就来看一下测试过程及结果。

测试程序如下:

说明1:由于读数据库语句调用简单的封包函数两次,所以把读文件也改成连续调用两次,数据库记录ID为1就在第一条,并且唯一索引。

说明2:测试两次一次是4K数据,一次是整形数据

  1 set_time_limit(0);  2   3 function fnGet($filename)  4   5 {  6   7 $content = file_get_contents($filename);  8   9 return $content; 10  11 } 12  13 function fnGetContent($filename) 14  15 { 16  17 $content = fnGet($filename); 18  19 return $content; 20  21 } 22  23 $times=100000; 24  25 echo '数据库查询结果:<br>'; 26  27 //--------------------------------- 28  29 $begin=fnGetMicroTime(); 30  31 for($i=0;$imydb_query("SELECT log_Content FROM blog WHERE log_ID='1'"); 36  37 $row=$dbcon->mydb_fetch_row($res); 38  39 $content=$row[0]; 40  41 } 42  43 echo 'fetch_row '.$times.' 次时间:<font color="red">'.(fnGetMicroTime()-$begin).'</font>秒<br>'; 44  45 //--------------------------------- 46  47 $begin=fnGetMicroTime(); 48  49 for($i=0;$imydb_query("SELECT log_Content FROM blog WHERE log_ID='1'"); 54  55 $row=$dbcon->mydb_fetch_array($res); 56  57 $content=$row['log_Content']; 58  59 } 60  61 echo 'fetch_array '.$times.' 次时间:<font color="red">'.(fnGetMicroTime()-$begin).'</font>秒<br>'; 62  63 //--------------------------------- 64  65 $begin=fnGetMicroTime(); 66  67 for($i=0;$imydb_query("SELECT log_Content FROM blog WHERE log_ID='1'"); 72  73 $row=$dbcon->mydb_fetch_object($res); 74  75 $content=$row->log_Content; 76  77 } 78  79 echo 'fetch_object '.$times.' 次时间:<font color="red">'.(fnGetMicroTime()-$begin).'</font>秒<br>'; 80  81 //--------------------------------- 82  83 $dbcon->mydb_free_results(); 84  85 $dbcon->mydb_disconnect(); 86  87 fnWriteCache('test.txt',$content); 88  89 echo '直接读文件测试结果:<br>'; 90  91 //--------------------------------- 92  93 $begin=fnGetMicroTime(); 94  95 for($i=0;$i'.(fnGetMicroTime()-$begin).'秒<br>';104 105 //---------------------------------106 107 $begin=fnGetMicroTime();108 109 for($i=0;$i'.(fnGetMicroTime()-$begin).'秒<br>';

4K大小数据的查询结果:

fetch_row 100000 次时间:16.737720012665秒

fetch_array 100000 次时间:16.661195993423秒

fetch_object 100000 次时间:16.775065898895秒

直接读文件测试结果:

file_get_contents直接读100000次时间:5.4631857872009秒

fopen直接读100000次时间:11.463611125946秒

整形ID查询结果:

fetch_row 100000 次时间:12.812072038651秒

fetch_array 100000 次时间:12.667390108109秒

fetch_object 100000 次时间:12.988099098206秒

直接读文件测试结果:

file_get_contents直接读100000次时间:5.6616430282593秒

fopen直接读100000次时间:11.542816877365秒

 

测试结论:

1、直接读文件相比数据库查询效率更胜一筹,而且文中还没算上连接和断开的时间。

2、一次读取的内容越大,直接读文件的优势会越明显(读文件时间都是小幅增长,这跟文件存储的连续性和簇大小等有关系),这个结果恰恰跟天缘预料的相反,说明MYSQL对更大文件读取可能又附加了某些操作(两次时间增长了近30%),如果只是单纯的赋值转换应该是差异偏小才对。

3、写文件和INSERT几乎不用测试就可以推测出,数据库效率只会更差。

4、很小的配置文件如果不需要使用到数据库特性,更加适合放到独立文件里存取,无需单独创建数据表或记录,很大的文件比如图片、音乐等采用文件存储更为方便,只把路径或缩略图等索引信息放到数据库里更合理一些。

5、PHP上如果只是读文件,file_get_contents比fopen、fclose更有效率,不包括判断存在这个函数时间会少3秒左右。

6、fetch_row和fetch_object应该是从fetch_array转换而来的,我没看过PHP的源码,单从执行上就可以说明fetch_array效率更高,这跟网上的说法似乎相反。

实际上在做这个试验之前,从个人经验判断就有了大概的结果,测试完成后则有种豁然开朗的感觉。假定在程序效率和关键过程相当且不计入缓存等措施的条件下,读写任何类型的数据都没有直接操作文件来的快,不论MSYQL过程如何,最后都要到磁盘上去读这个“文件”(记录存储区等效),所以当然这一切的前提是只读内容,无关任何排序或查找操作。

 

转载于:PHP程序猿的笔记 http://www.songchaoke.cn

bitsCN.com
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
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

MySQL: How to Add a User RemotelyMySQL: How to Add a User RemotelyMay 12, 2025 am 12:10 AM

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

The Ultimate Guide to MySQL String Data Types: Efficient Data StorageThe Ultimate Guide to MySQL String Data Types: Efficient Data StorageMay 12, 2025 am 12:05 AM

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

MySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMay 11, 2025 am 12:13 AM

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

MySQL: Should I use root user for my product?MySQL: Should I use root user for my product?May 11, 2025 am 12:11 AM

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQL String Data Types Explained: Choosing the Right Type for Your DataMySQL String Data Types Explained: Choosing the Right Type for Your DataMay 11, 2025 am 12:10 AM

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft