关于php单引号和双引号的使用

本人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更快呢?请大侠纠正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值