php中读写文件与读写数据库的效率比较分享
一直以来大家都把一些不经常修改的数据保存为文件来调用,看来还是比较正确的,直接读文件相比数据库查询效率更胜一筹,而且文中还没算上连接和断开的时间
这个问题也是最近才想到的,就是到底读文件更快还是读数据库更快,能快多少,天缘也搜索过,没见有网友就这个问题答复过,也可能是太简单的缘故,我们本文还是来实测一下,由于时间关系,VC还没装,天缘先用PHP测试了一下,,下次有时间在C/C++上补充测试到本文来,因为PHP的底层解析应该也是基于C的,所以估计两者环境测试结果差不多,小问题大收获,现在就来看一下测试过程及结果。
测试程序如下:
说明1:由于读数据库语句调用简单的封包函数两次,所以把读文件也改成连续调用两次,数据库记录ID为1就在第一条,并且唯一索引。
说明2:测试两次一次是4K数据,一次是整形数据
复制代码 代码如下:
set_time_limit(0);
function fnGet($filename)
{
$content = file_get_contents($filename);
return $content;
}
function fnGetContent($filename)
{
$content = fnGet($filename);
return $content;
}
$times=100000;
echo '数据库查询结果:
';
//---------------------------------
$begin=fnGetMicroTime();
for($i=0;$i{
$res=$dbcon->mydb_query("SELECT log_Content FROM blog WHERE log_ID='1'");
$row=$dbcon->mydb_fetch_row($res);
$content=$row[0];
}
echo 'fetch_row '.$times.' 次时间:'.(fnGetMicroTime()-$begin).'秒
';
//---------------------------------
$begin=fnGetMicroTime();
for($i=0;$i{
$res=$dbcon->mydb_query("SELECT log_Content FROM blog WHERE log_ID='1'");
$row=$dbcon->mydb_fetch_array($res);
$content=$row['log_Content'];
}
echo 'fetch_array '.$times.' 次时间:'.(fnGetMicroTime()-$begin).'秒
';
//---------------------------------
$begin=fnGetMicroTime();
for($i=0;$i{
$res=$dbcon->mydb_query("SELECT log_Content FROM blog WHERE log_ID='1'");
$row=$dbcon->mydb_fetch_object($res);
$content=$row->log_Content;
}
echo 'fetch_object '.$times.' 次时间:'.(fnGetMicroTime()-$begin).'秒
';
//---------------------------------
$dbcon->mydb_free_results();
$dbcon->mydb_disconnect();
fnWriteCache('test.txt',$content);
echo '直接读文件测试结果:
';
//---------------------------------
$begin=fnGetMicroTime();
for($i=0;$i{
$content = fnGetContent('test.txt');
}
echo 'file_get_contents直接读'.$times.'次时间:'.(fnGetMicroTime()-$begin).'秒
';
//---------------------------------
$begin=fnGetMicroTime();
for($i=0;$i{
$fname = 'test.txt';
if(file_exists($fname))
{
$fp=fopen($fname,"r");//flock($fp,LOCK_EX);
$file_data=fread($fp, filesize($fname));//rewind($fp);
fclose($fp);
}
$content = fnGetContent('test.txt');
}
echo 'fopen直接读'.$times.'次时间:'.(fnGetMicroTime()-$begin).'秒
';
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过程如何,最后都要到磁盘上去读这个“文件”(记录存储区等效),所以当然这一切的前提是只读内容,无关任何排序或查找操作。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The new Task Manager in Windows 11 22H2 is a boon for power users. It now provides a better UI experience with additional data to keep tabs on your running processes, tasks, services, and hardware components. If you've been using the new Task Manager, you may have noticed the new productivity mode. what is it? Does it help improve the performance of Windows 11 systems? Let’s find out! What is Productivity Mode in Windows 11? Productivity mode is one of the tasks in Task Manager

DeepMind’s AI agent is at work again! Pay attention, this guy named BBF mastered 26 Atari games in just 2 hours. His efficiency is equivalent to that of humans, surpassing all his predecessors. You know, AI agents have always been effective in solving problems through reinforcement learning, but the biggest problem is that this method is very inefficient and requires a long time to explore. Picture The breakthrough brought by BBF is in terms of efficiency. No wonder its full name can be called Bigger, Better, or Faster. Moreover, it can complete training on only a single card, and the computing power requirements are also much reduced. BBF was jointly proposed by Google DeepMind and the University of Montreal, and the data and code are currently open source. The highest attainable human

PyCharm is a powerful Python integrated development environment (IDE) that is widely used by Python developers for code writing, debugging and project management. In the actual development process, most developers will face different problems, such as how to improve development efficiency, how to collaborate with team members on development, etc. This article will introduce a practical guide to remote development of PyCharm to help developers better use PyCharm for remote development and improve work efficiency. 1. Preparation work in PyCh

StableDiffusion is an open source deep learning model. Its main function is to generate high-quality images through text descriptions, and supports functions such as graph generation, model merging, and model training. The operating interface of the model can be seen in the figure below. How to generate a picture. The following is an introduction to the process of creating a picture of a deer drinking water. When generating a picture, it is divided into prompt words and negative prompt words. When entering the prompt words, you must describe it clearly and try to describe the scene, object, style and color you want in detail. . For example, instead of just saying "the deer drinks water", it says "a creek, next to dense trees, and there are deer drinking water next to the creek". The negative prompt words are in the opposite direction. For example: no buildings, no people , no bridges, no fences, and too vague description may lead to inaccurate results.

Chromium-based browsers like Edge use a lot of resources, but you can enable efficiency mode in Microsoft Edge to improve performance. The Microsoft Edge web browser has come a long way since its humble beginnings. Recently, Microsoft added a new efficiency mode to the browser, which is designed to improve the overall performance of the browser on PC. Efficiency mode helps extend battery life and reduce system resource usage. For example, browsers built with Chromium, such as Google Chrome and Microsoft Edge, are notorious for hogging RAM and CPU cycles. Therefore, in order

With the rapid development of the Internet, the importance of databases has become increasingly prominent. As a Java developer, we often involve database operations. The efficiency of database transaction processing is directly related to the performance and stability of the entire system. This article will introduce some techniques commonly used in Java development to optimize database transaction processing efficiency to help developers improve system performance and response speed. Batch insert/update operations Normally, the efficiency of inserting or updating a single record into the database at one time is much lower than that of batch operations. Therefore, when performing batch insert/update

Title: Python makes life more convenient: Master this language to improve work efficiency and quality of life. As a powerful and easy-to-learn programming language, Python is becoming more and more popular in today's digital era. Not just for writing programs and performing data analysis, Python can also play a huge role in our daily lives. Mastering this language can not only improve work efficiency, but also improve the quality of life. This article will use specific code examples to demonstrate the wide application of Python in life and help readers

The role of subnet mask and its impact on network communication efficiency Introduction: With the popularity of the Internet, network communication has become an indispensable part of modern society. At the same time, the efficiency of network communication has also become one of the focuses of people's attention. In the process of building and managing a network, subnet mask is an important and basic configuration option, which plays a key role in network communication. This article will introduce the role of subnet mask and its impact on network communication efficiency. 1. Definition and function of subnet mask Subnet mask (subnetmask)
