code

인라인 문자열 사용과 php5에서 연결의 속도 차이는 무엇입니까?

codestyles 2020. 12. 26. 10:06
반응형

인라인 문자열 사용과 php5에서 연결의 속도 차이는 무엇입니까?


(php5 가정) 고려

<?php

    $foo = 'some words';

    //case 1
    print "these are $foo";

    //case 2
    print "these are {$foo}";

    //case 3
    print 'these are ' . $foo;
?>

1과 2 사이에 많은 차이가 있습니까?

그렇지 않다면 1/2에서 3 사이는 어떨까요?


모든 "실생활에서 더 빠를 수있는"질문과 마찬가지로 실제 테스트를 이길 수는 없습니다.

function timeFunc($function, $runs)
{
  $times = array();

  for ($i = 0; $i < $runs; $i++)
  {
    $time = microtime();
    call_user_func($function);
    $times[$i] = microtime() - $time;
  }

  return array_sum($times) / $runs;
}

function Method1()
{ 
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are $foo";
}

function Method2()
{
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are {$foo}";
}

function Method3()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are " . $foo;
}

print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";

모든 것을 페이징하기 위해 몇 번 실행 한 다음 ...

0.0035568

0.0035388

0.0025394

따라서 예상대로 보간은 사실상 동일합니다 (보간 엔진이 처리해야하는 추가 문자로 인한 노이즈 수준 차이). 직선 연결은 속도의 약 66 %로 큰 충격이 아닙니다. 보간 파서가 살펴보고 할 일이없는 것을 찾은 다음 간단한 내부 문자열 연결로 완료합니다. concat이 비싸더라도 변수를 구문 분석하고 원래 문자열을 잘라내거나 복사하기위한 모든 작업을 마친 후에 보간 기는 여전히이를 수행해야 합니다.

Somnath의 업데이트 :

위의 실시간 논리에 Method4 ()를 추가했습니다.

function Method4()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = 'these are ' . $foo;
}

print timeFunc('Method4', 10) . "\n";

Results were:

0.0014739
0.0015574
0.0011955
0.001169

문자열 만 선언하고 해당 문자열도 구문 분석 할 필요가없는 경우 구문 분석을 위해 PHP 디버거를 혼동해야하는 이유는 무엇입니까? 나는 당신이 내 요점을 이해하기를 바랍니다.


성능 차이는 최소한 2012 년 1 월 이후 관련없었 으며 그 이전 일 가능성이 높습니다.

Single quotes: 0.061846971511841 seconds
Double quotes: 0.061599016189575 seconds

이전 버전의 PHP는 차이가있을 수 있습니다. 개인적으로 큰 따옴표보다 작은 따옴표를 선호하므로 편리한 차이였습니다. 이 기사의 결론은 다음과 같은 훌륭한 포인트를 제공합니다.

스스로 위조하지 않은 통계를 절대 믿지 마십시오.

(기사에이 문구가 인용되어 있지만, 원래 quip은 처칠을 거짓말 쟁이로 묘사하기 위해 Joseph Goebbels의 선전 사역에 의해 발명 된 Winston Churchill 이 잘못 기인 한같습니다.

Ich traue keiner Statistik, die ich nicht selbst gefälscht habe.

이것은 느슨하게 "내가 속이지 않은 통계를 신뢰하지 않습니다."로 해석됩니다.)


라이브 벤치 마크 :

http://phpbench.com/

작은 따옴표와 큰 따옴표로 변수를 연결할 때 실제로 미묘한 차이가 있습니다.


@Adam의 테스트 사용

"these are " . $foo

다음은 더 빠릅니다.

'these are ' . $foo;

이것은 큰 따옴표로 묶인 "문자열"이 평가되기 때문입니다. 여기서 작은 따옴표로 묶인 '문자열'은 그대로 사용됩니다.


PHP에서 문자열 연산을 최적화하는 데 너무 몰두하지 마십시오. 데이터베이스 쿼리가 제대로 작성되지 않았거나 어떤 종류의 캐싱 체계도 사용하지 않는 경우 연결과 보간은 의미가 없습니다 (실제 성능에서). 나중에 코드를 디버깅하기 쉽고 성능 차이는 무시할 수있는 방식으로 문자열 작업을 작성하십시오.

@uberfuzzy 이것이 언어 세부 사항에 대한 질문이라고 가정하면 괜찮다고 생각합니다. 저는 실제 응용 프로그램에서 작은 따옴표, 큰 따옴표 및 heredoc 간의 성능을 잘못된 데이터베이스 쿼리와 같은 실제 성능 저하와 비교할 때 의미가 없다는 대화에 추가하려고합니다.


실행 시간의 차이는 완전히 무시할 수 있습니다.

참조하십시오

이와 같은 마이크로 최적화에 시간을 낭비하지 마십시오. 프로파일 러를 사용하여 실제 시나리오에서 애플리케이션의 성능을 측정 한 다음 실제로 필요한 부분을 최적화하십시오. 단일 조잡한 DB 쿼리를 최적화하면 코드 전체에 마이크로 최적화를 적용하는 것보다 성능이 더 향상 될 수 있습니다.


나는 포럼 소프트웨어 개발자 인 Vanilla가 그의 코드에있는 모든 큰 따옴표를 작은 따옴표로 대체하고 상당한 성능 향상을 발견 한 것을 기억하는 것 같습니다.

지금은 토론에 대한 링크를 찾을 수없는 것 같습니다.


변수를 연결할 때 차이가 있습니다 ... 그리고 결과로 무엇을하고 있는지 ... 그리고 만약 당신이하고있는 일이 그것을 출력으로 덤핑하는 것이라면, 출력 버퍼링이 켜져 있는지 여부.

also, what is the memory situation of the server? typically memory management on a higher level platform is worse than that at lower platforms...

$a = 'parse' . $this; 

is managing memory at the user code platform level...

$a = "parse $this";

is managing memory at the php system code platform level...

so these benchmarks as related to CPU don't tell the full story.

running the benchmark 1000 times vs running the benchmark 1000 times on a server that is attempting to run that same simulation 1000 times concurrently... you might get drastically different results depending on the scope of the application.


Double quotes can be much slower. I read from several places that that it is better to do this

'parse me '.$i.' times'

than

"parse me $i times"

Although I'd say the second one gave you more readable code.


Just to add something else to the mix, if you are using a variable inside a double quoted string syntax:

$foo = "hello {$bar}";

is faster than

$foo = "hello $bar";

and both of these are faster than

$foo = 'hello' . $bar; 

Practically there is no difference at all! See the timings: http://micro-optimization.com/single-vs-double-quotes


It should be noted that, when using a modified version of the example by Adam Wright with 3 variables, the results are reversed and the first two functions are actually faster, consistently. This is with PHP 7.1 on CLI:

function timeFunc($function, $runs)
{
    $times = array();

    for ($i = 0; $i < $runs; $i++)
    {
        $time = microtime();
        call_user_func($function);
        @$times[$i] = microtime() - $time;
    }

    return array_sum($times) / $runs;
}

function Method1()
{ 
    $foo = 'some words';
    $bar = 'other words';
    $bas = 3;
    for ($i = 0; $i < 10000; $i++)
         $t = "these are $foo, $bar and $bas";
}

function Method2()
{
    $foo = 'some words';
    $bar = 'other words';
    $bas = 3;
    for ($i = 0; $i < 10000; $i++)
         $t = "these are {$foo}, {$bar} and {$bas}";
}

function Method3()
{
    $foo = 'some words';
    $bar = 'other words';
    $bas = 3;
    for ($i = 0; $i < 10000; $i++)
         $t = "these are " . $foo . ", " . $bar . " and " .$bas;
}

print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";

I've also tried with '3' instead of just the integer 3, but I get the same kind of results.

With $bas = 3:

0.0016254
0.0015719
0.0019806

With $bas = '3':

0.0016495
0.0015608
0.0022755

It should be noted that these results vary highly (I get variations of about 300%), but the averages seem relatively steady and almost (9 out of 10 cases) always show a faster execution for the 2 first methods, with Method 2 always being slightly faster than method 1.

In conclusion: what is true for 1 single operation (be it interpolation or concatenation) is not always true for combined operations.

ReferenceURL : https://stackoverflow.com/questions/482202/is-there-a-performance-benefit-single-quote-vs-double-quote-in-php

반응형