[PHP] String의 올바른 활용법

8458 단어 phpphp

다른 사람들이 짠 코드들을 보고있다 보면 가끔 이와 같은 코드들을 볼 수 있다.

echo "print $var";

아무리봐도 에러를 내뱉을 것만 같은 코드인데 실행이 된다.
이런부분에서 나는 PHP는 어떻게 되먹은 언어인가 하고 감탄하게된다...

Psy Shell v0.10.8 (PHP 8.0.8 — cli) by Justin Hileman
>>> $var = "이게 출력이 된다고요?";
=> "이게 출력이 된다고요?"
>>> echo "print $var";
print 이게 출력이 된다고요?⏎

이러한 코드들은 아무리 봐도 가독성을 떨어트리고 나중에 문제가 될 가능성이 높아보여서 이렇게 사용하면 안되는 이유들을 찾아보았다.

PHPDoc.types.string
만약 "안에서 해당 기호를 ($) 마주하게되면, 파서는 해당 변수를 형성하기 위해 탐욕스럽게 많은 자원을 가져갈 것이다.

PSR-2
'"? 는 똑같이 동작합니다.
'를 사용하시고 안의 HTML 구문이나 변수에는 "를 사용하는걸 추천합니다.
빈 공간 앞뒤로 .를 사용하세요.

PSR-2에서는 . 를 이용하여 문자열 결합을 이용하라고 되어있다.
하지만 난 이렇게 .를 이용한 결합도 가독성을 떨어트린다고 생각한다.
그래서 내 주장을 뒷받침해줄 자료를 찾던 도중 알맞는 자료를 발견하였다.

성능상의 이슈

PHPDoc.types.string.John의 댓글

실행환경

php -v
PHP 7.0.12 (cli) (built: Oct 14 2016 09:56:59) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

100 million iterations (a test intended to see which one of the two {var} and {var} double-quote styles is faster)

$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
67048ms (38.2% slower)

$outstr = "literal$n$data$int$data$float$n";
49058ms (1.15% slower)

$outstr = "literal{$n}{$data}{$int}{$data}{$float}{$n}"
49221ms (1.49% slower)

$outstr = "literal${n}${data}${int}${data}${float}${n}"
48500ms (fastest; the differences are small but this held true across multiple runs of the test, and this was always the fastest variable encapsulation style)

1억번의 테스트 결과를 보면 string과 변수를 함께 사용할 때에는 "${var}" 와 같은 방식이 보다 좋은 성능을 보인다.
.를 이용한 결합방법은 가장 낮은 퍼포먼스를 보여준다.

그렇다면 "${var}""{$var}""$var"보다 쓰기 좋은거 아닌가요? 라는 질문이 나올 수 있다.
해당 댓글의 작성자는 테스트로 알 수 있는점을 이렇게 정리해놓았다.

  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->awesome()}!".You cannot do that with the "${var}" style.
    변수를 "This is a {$variable} notation" 이와 같이 사용하라, 왜냐하면 "This {$var['foo']} is {$obj->awesome()}!" 이와 같은 복잡한 확장이 필요할 때 가장 빠른 메소드다. "${var}" 이와 같은 스타일로는 그렇게 할 수가 없다.
  3. Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1 billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal.
    리터럴 비파싱 문자열을 원할 때 배열 키/값, 변수 값 등과 같은 완전한 문자열에 대해 작은따옴표를 사용하는 것이 좋다. 하지만 1.55%의 측정 가능한 차이를 찾기 위해 10억 번 반복해야 했다. 그래서 제가 리터럴에 따옴표를 붙인 문자열을 사용하는 유일한 진짜 이유는 코드 청결을 위해서다. 문자열이 문자 그대로라는 것을 확실히 하기 위해서
  4. If you think another method such as sprintf() or 'this'.$var.'style' is more readable, and you don't care about maximizing performance, then feel free to use whatever concatenation method you prefer!
    sprintf()나 'this'.$var. 'style'와 같은 다른 방법을 생각할 경우는 더욱 읽기 쉽고 성능을 극대화하는 데 신경 쓰지 않는다면 원하는 연결 방법을 자유롭게 사용하십시오!

이러한 이유들을 봤을 때 "{$var} print"와 같은 방식으로 php string을 사용하는 것이 제일 괜찮은 방법이 아닐까 싶다.

좋은 웹페이지 즐겨찾기