本人php初学者
一直以为php中单引号比双引号快,我今天测试了一下
因为主要是拼写sql语句的时候 不知道该用哪种,
单引号用点拼接,参数需要先进行处理。
双引号,里面写变量,会自动转义掉参数中的单引号
我先写了个简单的测试
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return $usec + $sec;
}
function test1() {
$name = '你\'好';
$sex = 1;
$address = '撒缴费卡啊数据库\'flash奥斯卡级疯狂拉升就疯狂拉升风口浪尖萨克浪费';
$name = mysql_escape_string($name);
$address = mysql_escape_string($address);
$sql = 'insert into userinfo(name,sex,address) values(\''
. $name . '\',\''
. $sex . '\',\''
. $address . '\')';
}
function test11() {
$name = '你\'好';
$sex = 1;
$address = '撒缴费卡啊数据库\'flash奥斯卡级疯狂拉升就疯狂拉升风口浪尖萨克浪费';
$sql = 'insert into userinfo(name,sex,address) values(\''
. $name . '\',\''
. $sex . '\',\''
. $address . '\')';
}
function test2() {
$name = '你\'好';
$sex = 1;
$address = '撒缴费卡啊数据库\'flash奥斯卡级疯狂拉升就疯狂拉升风口浪尖萨克浪费';
$name = mysql_escape_string($name);
$address = mysql_escape_string($address);
$sql = "insert into userinfo(name,sex,address) values('$name','$sex','$address')";
}
function test21() {
$name = '你\'好';
$sex = 1;
$address = '撒缴费卡啊数据库\'flash奥斯卡级疯狂拉升就疯狂拉升风口浪尖萨克浪费';
$sql = "insert into userinfo(name,sex,address) values('$name','$sex','$address')";
}
test1();
test11();
test2();
test21();
$count = 1000000;
echo '开始测试:' . $count;
//单引号速度测试
$begin = microtime_float();
for ($index = 0; $index < $count; $index++) {
test1();
}
$end = microtime_float();
echo '<br/>单引号' . ($end - $begin);
//双引号测试
$begin = microtime_float();
for ($index = 0; $index < $count; $index++) {
test11();
}
$end = microtime_float();
echo '<br/>单引号无特殊处理' . ($end - $begin);
//双引号测试
$begin = microtime_float();
for ($index = 0; $index < $count; $index++) {
test2();
}
$end = microtime_float();
echo '<br/>双引号' . ($end - $begin);
//双引号测试(不进行特殊自付处理)
$begin = microtime_float();
for ($index = 0; $index < $count; $index++) {
test21();
}
$end = microtime_float();
echo '<br/>双引号无特殊处理' . ($end - $begin);
?>
为了保证是测试sql语句拼接部分,所以几个方法内的变量声明一直。
通常使用中会用到test1()和test21()这两种形式,功能一样,都是拼接sql语句并保证单引号不会拆段sql语句
一下是测试结果
开始测试:1000000
单引号2.240818977356
单引号无特殊处理1.4319710731506
双引号2.1632540225983
双引号无特殊处理1.3699610233307
php 5.2.14
有点不解啊,那个测试是不是意味着我用双引号拼接sql更快呢?请大侠纠正。