//双引号:
$sql = "select * from user where id=$uid and type=".$type;//单引号:
$sql = 'select * from user where id='.$uid.' and type='.$type;
我在写SQL语句的时候,经常碰到这个头疼的问题.
网上说单引号解析字符串速度快N倍,
但是双引号的话,写SQL语句更方面. 到底用哪个呢? 求解释求指导.
$sql = "select * from user where id=$uid and type=".$type;//单引号:
$sql = 'select * from user where id='.$uid.' and type='.$type;
我在写SQL语句的时候,经常碰到这个头疼的问题.
网上说单引号解析字符串速度快N倍,
但是双引号的话,写SQL语句更方面. 到底用哪个呢? 求解释求指导.
这个快 你很意外吧 不要相信网上什么单引号不需要解析双引号需要解析 所以双引号比单引号速度快 都是人云亦云我刚才做了个简单测试
echo "张三,$a";echo '张三,'.$a;循环50万次 双引号的速度26 单引号的速度65 你说那个快?
for ($i=0;$i<50000;$i++){
$v='abc';
$str='str:'.$v;
echo $str;
}第一次:单引号:
usage:0.026096105575562双引号:
usage:0.02674388885498第二次:
单:usage:0.026987075805664
双:usage:0.027086973190308第三次:
单:usage:0.025830984115601
双:usage:0.02665901184082
我的做法是 SQL 一律使用双引号.变量一律使用单引号.
结果自己试试....单引号的确比双引号要分析转义的东西少,但是看看这个句子:
'select * from user where id='.$uid.' and type='.$type;
这有2个字串,2个变量,3个连接操作......
和下面这行,1个字串,内置两个变量,比起来
"select * from user where id={$uid} and type={$type}";
究竟谁快,还真说不清....
这和字串长度,字串复杂度,变量类型,变量内容,应该都有关系.....我的建议,不管初学还是所谓的高手,都不要在这些地方浪费时间了......
搞清楚单双引号的解析规律,比所谓的速度要重要,
对多变量的字串来说,双引号显然可读性更好,我也基本按照8楼的习惯. 你优化一个低效sql得到的效率提升,会超过你改10000个引号.....所以无论网上还是面试官那些所谓的效率问题,很多都是胡说或人云亦云,写程序的时候不要过多提前考虑效率,而是应该通过测试做有针对性的优化..有兴趣可以搜索"过早优化",结果一目了然<?php$a1='this';
$a2='just';
$a3='test';
$a4='ok';getRunTime();$x='';
for($i=0;$i<10000;$i++){
$x.="this is just a test string";
}echo getRunTime()."\n";$x='';
for($i=0;$i<10000;$i++){
$x.='this is just a test string';
}echo getRunTime()."\n";$x='';
for($i=0;$i<10000;$i++){
$x.="{$a1} is {$a2} a {$a3} string, {$a4}";
}echo getRunTime()."\n";$x='';
for($i=0;$i<10000;$i++){
$x.=$a1.' is '.$a2.' a '.$a3.' string, '.$a4;
}echo getRunTime()."\n";function getRunTime(){
static $time;
$now=microtime(true);
$r=($now-$time)*1000;
$time=$now;
return $r;
}
$sql = "select * from user where id='$uid' and type='$type'";