Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial php程序优化求建议,执行速度太慢

php程序优化求建议,执行速度太慢

Jun 23, 2016 pm 02:13 PM

本帖最后由 zhuzhaodan 于 2013-06-12 18:06:26 编辑

现有 四级词库4000单词txt文档,格式如下
accent n.口音,腔调;重音 
acceptable a.可接受的,合意的 
acceptance n.接受,验收;承认 
access n.接近;通道,入口 
accessory n.同谋,从犯;附件 
accident n.意外的;事故 
accidental a.偶然的;非本质的 

现要把英汉分离后分别插入mySQL数据库内,代码如下
<?phpheader("Content-type: text/html; charset=utf-8");$file = dirname(__FILE__)."/siji.txt";  //四级词库文件if(!file_exists($file)){	echo 'Not exist';}else {	$a = array();//存放英汉对照对儿的数组	$lines = file($file);//读取txt到数组,一行为一个英汉对照对	foreach ($lines as $k=>$v){		if(preg_match('/[a-zA-Z]/',$v))//有的行是标题之类的,不是英汉对照,判断后不加到数组a里面			$a[$k] = trim($v);//因为有换行符,去掉	}	$b = array();//2维数组,$b[n][0]为英文,$b[n][1]为释义	foreach($a as $k=>$v){//把a数组的英汉分离,填充到b数组的第二维内		preg_match('/([a-zA-Z]*)\s(.*)/',$v,$matches);//正则英汉分离,matches[1]是英文,matches[2]是释义中文		$b[$k][0] = $matches[1];		$b[$k][1] = $matches[2];	}	$dsn = 'mysql:host=localhost;dbname=test1';	$db = new PDO($dsn,'root','',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8'));	foreach($b as $k=>$v){//插入数据库		$db->exec("INSERT INTO siji (en,cn) VALUES ('$v[0]','$v[1]')");//数据库3个字段,id,en是英文,cn是中文	}		}
Copy after login


程序执行时间2分钟左右,求优化建议~我自己感觉正则那部分应该优化不了多少,主要感觉插进数据库这里费时太多,各位高人有方法请不吝赐教,现在程序执行完毕需要 120秒,希望最终优化后能到10秒内,谢谢,4级词库一共才4000对词组,120秒太长了

最终效果图:


高人们,因为我比较新手,所以不管从代码上,还是整体思路上都使这个程序运行缓慢,求优化建议,特别是 数据库这里,还有 数组这里,或者有 更好的办法。100分在这里,谢谢!


回复讨论(解决方案)

不一定能满足要求,但肯定比你的快

$ar = array_map('trim', file('siji.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ));foreach($ar as $v){  preg_match('/([a-zA-Z]*)\s(.*)/', $v, $r);  if(isset($r[2])) $b[] = "('$r[1]','$r[2]')";}$dsn = 'mysql:host=localhost;dbname=test1';$db = new PDO($dsn,'root','',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8'));$db->exec('INSERT INTO siji (en,cn) VALUES ' . join(',', $b));
Copy after login
Copy after login

说一说我的想法,
也不知道效率怎么样,
不用数组,也不用循环。
首先用 file_get_contents 将文件读取为字符串,
然后 preg_replace 直接将整个字符串格式化为一个多语句sql,
接着执行一次就行了。

内存表 一次性写入数据库

1、将内容格式化成一个类似#1的插入sql语句,保存成*.sql
2、直接用mysql将上面的*.sql导入,php可以用exec

内存表 一次性写入数据库
求详解

mysql有个多行insert语句, 很多行集成到一个SQL语句, 效率比一行一条SQL语句高很多.
格式如下:
inser into (...) values (...),(...),...

不好意思, 上面insert少了个t
MySQL 的导出语句格式都是用多行insert. 导入速度很快. 一般一条语句2000行记录没问题

如果你的数据文件中的行都符合你示例的格式,那么就可以直接使用 MySQL 指令

LOAD DATA local INFILE '/路径/siji.txt' INTO TABLE siji  FIELDS TERMINATED BY ' ' (en, cn);
Copy after login

不一定能满足要求,但肯定比你的快

$ar = array_map('trim', file('siji.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ));foreach($ar as $v){  preg_match('/([a-zA-Z]*)\s(.*)/', $v, $r);  if(isset($r[2])) $b[] = "('$r[1]','$r[2]')";}$dsn = 'mysql:host=localhost;dbname=test1';$db = new PDO($dsn,'root','',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8'));$db->exec('INSERT INTO siji (en,cn) VALUES ' . join(',', $b));
Copy after login
Copy after login


我考虑了一下,用了预处理语句参数绑定
	$start = microtime(true);	$stmt = $db->prepare('INSERT INTO siji (en,cn) VALUES (:en,:cn)');	$stmt->bindParam(':en',$en);	$stmt->bindParam(':cn',$cn);	foreach($b as $k=>$v){//插入数据库		$en = $v[0];		$cn = $v[1];		$stmt->execute();//数据库3个字段,id,en是英文,cn是中文	}	echo microtime(true)-$start;//127秒
Copy after login

对比原来的代码
$start = microtime(true);	foreach($b as $k=>$v){//插入数据库		$db->exec("INSERT INTO siji (en,cn) VALUES ('$v[0]','$v[1]')");//数据库3个字段,id,en是英文,cn是中文	}	echo microtime(true)-$start;//116秒
Copy after login

居然还慢了11秒,不是说一样类型的语句,编译成sql模板后速度会提升么,为什么这里下降啊??太奇怪!

使用参数绑定时,PDO::quote(转义特殊字符)始终都会被执行,并不理会你的数据实际并不包含特殊字符
多出来的时间就是 PDO::quote 的执行时间

如果你总是单条插入,那么无论如何都不会“高速”运行的

居然还慢了11秒,不是说一样类型的语句,编译成sql模板后速度会提升么,为什么这里下降啊??太奇怪!
预编译的提升原理在于节省了编译本身的时间,你觉得一个简单的insert编译需要时间吗?

内存表 一次性写入数据库

感觉MySQL还是弱,貌似没有类似SQLServer的bulkCopy功能,SQLBulkCopy批量插入几万条数据也是瞬间的事
“内存表 一次性写入数据库”,具体怎么实现,跪求详解啊

连接成一个SQL语句再执行,速度会快很多的

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 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles