Php_codesniffer: Question/Request: Is there a sniff to detect the use of single quotes over double quotes?

Created on 11 Sep 2017  路  3Comments  路  Source: squizlabs/PHP_CodeSniffer

Related issue: #509

Rationale:
Relevant post to php.net/string_parsing

TLDR excluding percentage results:

php v7.0.12
Comparing concatenations and single / double quotes
Base test

$outstr = 'literal' . $n . $data . $int . $data . $float . $n; 
$outstr = "literal$n$data$int$data$float$n"; 
$outstr =<<<EOS 
literal$n$data$int$data$float$n 
EOS; 
$outstr = sprintf('literal%s%s%d%s%f%s', $n, $data, $int, $data, $float, $n); 
$outstr = sprintf('literal%s%5$s%2$d%3$s%4$f%s', $n, $int, $data, $float, $data, $n); 

Test types:

  1. Base test (1 million iterations)
  2. Base test adapted to compare adding a newline (PHP_EOL literal or n) (1 million iterations)
  3. ${var} vs {$var} double-quote styles (1 million iterations)
  4. 'literal string' vs "literal string" (1 billion iterations)

Result:
Double-quoted strings are almost always faster then single unless it is a purely literal string (and that was negligible: 1 billion iterations to find a 1.55% measurable difference)

So the "highest code performance" style rules are:

  1. Always use double-quoted strings for concatenation.
  2. Put your variables in "This is a {$variable} notation", because it's the fastest method which still allows complex expansions like "This {$var['foo']} is {$obj->bar()}!". You cannot do that with the "${var}" style.
  3. Feel free to use single-quotes for purely literal string since it is nearly equivalent (1.55% marginally better). Possible only real reason to use: code cleanliness - to make it clear that the string is literal.

or if you don't care about maximizing performance, use whatever you want

A replication of these tests for confirmation would be useful.

Request:

  • Double quotes over single quotes
  • property options to follow the 'highest code performance' style rules listed above

Most helpful comment

Is it possible to enforce double quote usage?

All 3 comments

Loosely related to #2259

coming from #2316 just to say that a first version without the "highest code performance" option would be nice since the code performance quotes preferences could change between version of php and the performance gain is so small anyway

Is it possible to enforce double quote usage?

Was this page helpful?
0 / 5 - 0 ratings