새소식

Welcome to the tech blog of Junior Backend Developer Myoungji Kim!

Development/PHP

PHP 코드 최적화 관련 팁 모음

  • -

📌 Tips

  • If a method can be static, declare it static. Speed improvement is by a factor of 4.
    static 메서드는 일반 메서드보다 4배 빠르다


  • echo is faster than print.
    echo가 print보다 빠르다


  • Set the maxvalue for your for-loops before and not in the loop.
    ➜ for 루프을 위핸 최대값(탈출조건)을 루프 안에서가 아니고 루프 시작 이전에 지정하라.


  • Unset your variables to free memory, especially large arrays.
    ➜ 메모리를 해제하기 위해 변수를 unset하라. 특히 커다란 배열은 그래야 된다.


  • Avoid magic like get, __set, __autoload
    get, __set, __autoload와 같은 마법을 피해라.


  • require_once() is expensive
    require_once()는 비싸다.


  • Use full paths in includes and requires, less time spent on resolving the OS paths.
    ➜ include와 require를 사용할 때, 경로를 찾는데 시간이 적게 걸리는 full path를 사용하라.


  • If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
    ➜ 스크립트가 언제 실행했는지 알고 싶으면 time()보다 $_SERVER[’REQUEST_TIME’]이 좋다.


  • See if you can use strncasecmp, strpbrk and stripos instead of regex
    ➜ 정규표현식보다는 가능하면 strncasecmp나 strpbrk, stripos를 사용하라.

    • strncasecmp: 두 문자열의 앞쪽 일부가 대소문자 구분없이 일치하는지 확인할 때 사용
    • strpbrk: 문자 집합에 속한 특정 문자가 문자열에 나타나는지 확인할 때 사용
    • stripos: 대소문자 구분없이 특정 문자열이 다른 문자열에 포함되는지 확인할 때 사용
  • str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
    str_replace가 preg_replace보다 빠르지만, strtr은 str_replace보다 4배 빠르다.


  • If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
    ➜ 만약 문자열 교체 같은 함수가 배열과 문자열을 인자로 받아들이면, 그리고 그 인자 리스트가 길지 않다면, 배열을 한 번에 받아들여서 처리하는 것 대신에 한 번에 문자열을 하나씩 넘겨서 처리하는 것을 고려해봐라.


  • It’s better to use select statements than multi if, else if, statements.
    ➜ 여러 개의 if/else if 문장 대신에 select/switch 문장을 사용하는 게 더 좋다.


  • Error suppression with @ is very slow.
    ➜ @를 이용한 에러 출력 방지는 매우 느리다.


  • $row[’id’] is 7 times faster than $row[id]
    ➜ $row[’id’]가 $row[id]보다 7배 빠르다.


  • Error messages are expensive
    ➜ 에러 메시지는 비싸다


  • Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
    for 루프의 표현식 안에서 함수를 사용하지 마라. for ($x = 0; $x < count($array); $x)에서 count() 함수가 매번 호출된다.


  • Incrementing a global variable is 2 times slow than a local var.
    ➜ 전역 변수를 증가시키는 것이 지역 변수를 증가시키는 것보다 2배 느리다.


  • Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
    ➜ 객체의 멤버변수를 증가시키는 것이 지역 변수를 증가시키는 것보다 3배 느리다.


  • Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
    ➜ 값이 지정되지 않은 지역 변수를 증가시키는 것이 미리 초기화된 변수를 증가시키는 것보다 9~10배 느리다.


  • Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
    ➜ 전역 변수를 함수 안에서 사용하지 않으면서 그저 선언하기만 해도 (지역 변수를 증가시키는 것만큼) 느려진다. PHP는 아마 전역 변수가 존재하는지 알기 위해 검사를 하는 것 같다.


  • Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
    ➜ 메쏘드 호출은 클래스 안에서 정의된 메쏘드의 갯수에 독립적인 듯 하다. 왜냐하면 10개의 메쏘드를 테스트 클래스에 추가해봤으나 성능에 변화가 없었기 때문이다.


  • Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
    ➜ 문자열을 이중 따옴표 대신에 단일 따옴표로 둘러싸는 것은 좀 더 빠르게 해석되도록 한다. 왜냐하면 PHP가 이중 따옴표 안의 변수를 찾아보지만 단일 따옴표 안에서는 변수를 찾지 않기 때문이다. 물론 문자열 안에서 변수를 가질 필요가 없을 때만 이렇게 사용할 수 있다.

🔗 참고자료

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.