http://www.think-techie.com/2010/04/php-web-development-tips-and-tricks.html


의 글을 번역한 글입니다.


그냥 심심해서 했던거에요.. 별 의미 없고, 번역을 잘 못하기 때문에 원문을 문단별로 첨부합니다.






There are a number of tricks that can make your life easier and help you to squeeze the last bit of performance from your scripts. These tricks won't make your web applications much faster, but can give you that little edge in performance you may be looking for. More importantly it may give you insight into how PHP internals works allowing you to write code that can be executed in more optimal fashion by the Zend Engine.


아래에 소개되는 내용들은  약간의 성능을 향상시키고 당신의 삶을 좀 더 편하게 해줄 수 있는 트릭들입니다. 이 트릭들은 당신의 웹 어플리케이션을 엄청 빠르게하진 않을 것입니다. 그러나 당신이 찾고 있던 약간의 성능 향상을 줄 수 있습니다. 좀 더 중요한 것은 당신에게 PHP의 내부가 어떻게 돌아가는지 영감을 주고 젠드 엔진에 최적화 된 개발 방식을 익힐 수 있을겁니다.


1. Static methods

If a method can be declared static, declare it static. Speed improvement is by a factor of 4.


1. Static 함수들

함수를 Static으로 선언할 수 있다면 Static으로 선언하세요. 속도 향상을 얻을 수 있습니다. (4번 참조)


2. echo() vs. print()

Even both of these output mechanism are language constructs, if you benchmark the two you will quickly discover that print() is slower then echo(). The reason for that is quite simple, print function will return a status indicating if it was successful or not (note: it does not return the size of the string), while echo simply print the text and nothing more. Since in most cases this status is not necessary and is almost never used it is pointless and simply adds unnecessary overhead.

view plaincopy to clipboardprint?

echo( 'Hello World' );    

// is better than    

print( 'Hello World' );    

2. echo() vs print()

두 출력 함수는 모두 언어 구조에 종속되어있지만, 당신이 직접 벤치마킹해본다면 print() 는 echo()보다 느리다는 걸 확인할 수 있을겁니다. 꽤나 간단한 이유인데, print 함수는 출력에 대한 결과값을 반환(성공했을 때는 스트링의 크기를, 실패했을 때는 반환하지 않습니다) 하지만 echo 는 단순히 텍스트를 출력해주기만 합니다. 대부분의 경우에 결과값은 필요하지 않고, 쓸데없는 오버헤드가 늘어나게 됩니다.


3. echo's multiple parameters

Use echo's multiple parameters instead of string concatenation. It's faster.

view plaincopy to clipboardprint?

echo 'Hello', ' ', 'World';    

// is better than    

echo 'Hello' . ' ' . 'World';   

Read more...


3. echo 에서 여러 개의 인자를 이용할 때

echo에서 여러개의 인자를 이용하는 것이 문자열 연쇄(붙이기)를 이용하는 것보다 빠릅니다.


4. Avoid the use of printf

Using printf() is slow for multitude of reasons and I would strongly discourage it's usage unless you absolutely need to use the functionality this function offers. Unlike print and echo printf() is a function with associated function execution overhead. More over printf() is designed to support various formatting schemes that for the most part are not needed in a language that is typeless and will automatically do the necessary type conversions. To handle formatting printf() needs to scan the specified string for special formatting code that are to be replaced with variables. As you can probably imagine that is quite slow and rather inefficient.

view plaincopy to clipboardprint?

echo 'Result:', $result;    

// is better than    

printf( "Result: %s", $result );    


4. printf 함수 사용 자제

printf() 함수는 여러 이유로 느려지며, 나는 꼭 써야 할 경우가 아니면 사용하지 않는 것을 강력 추천합니다. print와 echo와는 달리 printf는 오버헤드를 많이 실행시키는 기능입니다. 더욱이, printf() 는 타입이 없고, 필요하다면 알아서 타입이 변환되는 언어에서는 다양한 자료형을 지원하는 상황에서는 대부분의 경우 필요가 없습니다. printf() 함수를 다루기 위해서는 특수한 문자열과 특수한 형 코드를 대치하게 됩니다. 아마 당신은 상당히 느리고 비효율적이라고 생각하게 될 것입니다.

5. Single quotes vs. double quotes

In PHP there is a difference when using either single or double quotes, either ‘ or “. If you use double quotes ” then you are telling the code to check for a variable. If you are using single quotes ‘ then you are telling it to print whatever is between them. This might seem a bit trivial, but if you use the double quotes instead of the single quotes, it will still output correctly, but you will be wasting processing time.

view plaincopy to clipboardprint?

echo 'Result: ' . $var;    

// is better than    

echo "Result: $var";  

Even the use of sprintf instead of variables contained in double quotes, it’s about 10x faster.


Read more...


5. 작은따옴표(‘) 와 큰따옴표(‘’)

PHP에서 작은 따옴표와 큰 따옴표를 쓰는 것은 차이가 있습니다. 만약 큰 따옴표(“)를 쓸 때는 이것을 변수로 취급한다고 코드에게 말하는 것입니다. 당신이 작은 따옴표(‘)를 쓴다면 이것은 어디에 있던 단지 출력만을 위한 것으로 취급할 것입니다.


6. Methods in derived classes vs. base classes

Methods in derived classes run faster than ones defined in the base class.


5. 상속받은 클래스의 함수 vs 부모 클래스의 함수

상속받은 클래스의 함수가 부모 클래스의 함수보다 빠르다


7. Accessing arrays

e.g. $row['id'] is 7 times faster than $row[id]


7. 배열 접근

$row[‘id’] 는 $row[id] 로 접근하는 것보다 7배 빠르다

8. Do not implement every data structure as a class

Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory. For this reason, do not implement every data structure as a class, arrays are useful, too.


8. 모든 자료구조를 클래스로 구현하지 말아라

모든게 객체지향일 필요도 없고, 이건 가끔 꽤나 큰 오버헤드를 유발하며, 이런 메서드나 오브젝트 호출은 메모리를 엄청 잡아먹습니다. 이런 이유에서, 모든 자료구조를 클래스로 만들지는 마세요. 배열도 꽤나 쓸만합니다.

9. Avoid functions inside loops

Try to use functions outside loops. Otherwise the function may get called each time.


9. 루프 안에 함수 쓰는걸 피하라

함수 바깥에 함수를 호출하도록 노력하세요. 안그러면 매번 해당 함수를 호출합니다.

view plaincopy to clipboardprint?

// 예를 들어 for 루프 안에서 count() 함수를 제어조건에 호출한다면,

// 매 루프 순환마다 함수가 호출됩니다

$max = count( $array );    

for( $i = 0; $i < $max; $i++ )    

{    

   // 무언가를 하겠죠..

}    

   

// 위에께 아래거보다 나아요.

   

for( $i = 0; $i < count( $array ); $i++ )    

{    

   // 여기도 무언가를 하겠죠..

}  

It's even faster if you eliminate the call to count() AND the explicit use of the counter by using a foreach loop in place of the for loop.

이게 count() 함수를 호출하거나, foreach 루프의 counter를 사용하는거보단 훨씬 빠릅니다.

view plaincopy to clipboardprint?

foreach ($array as $i) {  

   // do something    

}  

Read more...


참고: 단일 인자로 함수를 호출하는 것과 내용이 없는 함수를 호출하는 것은 $localvar++ 연산을 7~8번 하는 것과 비슷합니다. 유사한 함수 호출도 15번의 $localvar++ 연산을 하는 것과 흡사합니다.


Note: A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about15 $localvar++ operations.


10. ?> <?

When you need to output a large or even a medium sized static bit of text it is faster and simpler to put it outside the of PHP. This will make the PHP's parser effectively skip over this bit of text and output it as is without any overhead. You should be careful however and not use this for many small strings in between PHP code as multiple context switches between PHP and plain text will ebb away at the performance gained by not having PHP print the text via one of it's functions or constructs.


10. ?><?

 당신이 크거나, 중간 정도 사이즈의 고정된 텍스트를 출력하려 할 때엔 PHP구문 바깥에 출력하는게 더 빠르고 간단합니다. 이 행동은 PHP 파서가 효과적으로 해당 구문을 무시하고 지나가 출력시 오버헤드를 없애줍니다.  이런 부분에 주의하며 성능적인 이슈를 위해서 고정된 텍스트들을 소스 코드 중간 중간에 넣는 것을 최대한 자제해야 합니다.

11. isset instead of strlen

When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using a isset() trick.


11. isset으로 strlen으로 대신하기

당신이 문자열이 충분한 길이를 갖고 있는지 확인해야 할 때 strlen() 함수를 사용해야 한다고 생각할 겁니다. 이 함수의 속도는 그럭저럭 봐줄만한 편인데 그렇다고 zval 구조(PHP에서 변수를 저장하는데 쓰이는 C 구조)의 길이를 바로 반환하는 건 아니고 뭔가 연산을 합니다. 어쨌든 strlen()은 뭔가 느린데, 이 함수가 lowercase 나 hashtable 검색같은 연산을 한다는겁니다. 그래서 isset()을 사용하는 트릭으로 속도를 향상시킬 수 있습니다.

view plaincopy to clipboardprint?

if (!isset($foo{5})) { echo "Foo is too short"; }  

// 이게 더 빨라요

if (strlen($foo) < 5) { echo "Foo is too short"; }  

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.


isset()함수를 호출하는게 strlen()함수를 호출하는게 더 빠른데, 왜냐하면 strlen()함수랑 isset()은 언어 구조적으로 다르고, isset은 lowercase나 hashtable 검색 연산을 필요로 하지 않기 때문입니다. 이 의미는 가상의 오버헤드를 줄이지만 실제로는 문자열의 길이를 알아낼 수 있다는 이야기입니다.

12. true is faster than TRUE

This is because when looking for constants PHP does a hash lookup for name as is. And since names are always stored lowercased, by using them you avoid 2 hash lookups. Furthermore, by using 1 and 0 instead of TRUE and FALSE, can be considerably faster.


12. true 는 TRUE 보다 빠르다

왜냐하면 PHP는 상수들을 hash에서 검색을 하기 때문인데, 이게 다 최종적으로는  소문자로 저장이 되어있습니다. 그러므로 2개의 hash 테이블을 검색하는 연산을 회피할 수 있습니다. 게다가, 1과 0을 TRUE와 FALSE를 이용하는거보다 더 빠를 수 있습니다.


13. Incrementing or decrementing the value of the variable

When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.


Additionally,


1. Incrementing a local variable in a method is the fastest. Nearly the same as calling alocal variable in a function.


2. Incrementing a global variable is 2 times slower than a local variable.


3. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.


4. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.


Read more ... and more...


13. 변수의 증감 연산

증감 연산을 변수에 할 때에 $i++은 ++$i 보다 느립니다. 이건 PHP에 한정된 이야기가 아니라 다른 언어에도 적용됩니다. ++$i  가 PHP에서 더 빠른 이유는 $i++는 4개의 opcode가 필요하지만 ++$i는 opcode가 3개가 필요합니다. 후위 증가 연산은 임시 변수를 생성한 후에 이걸 증가시키지만, 전위 증가 연산은 바로 원래의 값을 증가시키기 때문입니다. 이건 하나의 최적화로써 Zend’s PHP optimizer와 같은 것에는 적용이 되어있습니다. 이건 여전히 기억해봄직한 아이디어인데 꽤나 많은 ISP들은 코드 최적화 없이 작동하기 때문입니다.


추가적으로,


1. 함수 안 지역 변수의 증가가 제일 빠릅니다. 이건 그냥 지역 변수를 호출하는 것과 근사합니다.

2. 전역 변수 증가 연산은 지역 변수 증가 연산보다 2배 느립니다.

3. 객체 속성(예: $this->prop) 증가 연산은 지역 변수 증가 연산보다 3배 느립니다.

4. 정의되지 않은 변수에 대한 증가 연산은 정의된 변수에 대한 증가 연산보다 9~10배 느립니다.

14. Replace regex calls with ctype extension, if possible

Many scripts tend to reply on regular expression to validate the input specified by user. While validating input is a superb idea, doing so via regular expression can be quite slow. In many cases the process of validation merely involved checking the source string against a certain character list such as A-Z or 0-9, etc... Instead of using regex in many instances you can instead use the ctype extension (enabled by default since PHP 4.2.0) to do the same. The ctype extension offers a series of function wrappers around C's is*() function that check whether a particular character is within a certain range. Unlike the C function that can only work a character at a time, PHP function can operate on entire strings and are far faster then equivalent regular expressions.

view plaincopy to clipboardprint?

ctype_digit($foo);  

// is better than  

preg_match("![0-9]+!", $foo);  

14. 가능하다면 regex함수 호출을 ctype 확장으로 변경하세요.

많은 스크립트는 정표현식 사용자의 입력에 대하여 정규표현식으로 확인합니다. 입력값의 유효성을 정규표현식으로 체크하는 것은 꽤나 훌륭한 아이디어지만, 이게 꽤나 느릴 수 있습니다. 많은 경우 유효성 검사 연산에서 단지 이 문자열들이 A-Z, 0-9 같은 것으로 이루어져있는지를 체크하는데, regex를 사용하는 대신 ctype 확장을 이용하여 대체할 수 있습니다.(PHP 4.2.0 이상부터 사용이 가능합니다). ctype 확장은 C의 is뭐뭐뭐() 함수와 같은 기능을 제공하며 어떤 범위 내의 문자열로 작성되어있는지 검사합니다. C함수는 한 문자당 한 번 작동하지만, PHP함수는 문자열 전체를 검사할 수도 있고, 정규표현식에 비해서 훨씬 빠릅니다.


15. isset vs. in_array and array_key_exists

Another common operation in PHP scripts is array searching. This process can be quite slow as regular search mechanism such as in_array() or manual implementation work by iterating through the entire array. This can be quite a performance hit if you are searching through a large array or need to perform the searches frequently. So what can you do? Well, you can do a trick that relies upon the way that Zend Engine stores array data. Internally arrays are stored inside hash tables when they array element (key) is the key of the hashtables used to find the data and result is the value associated with that key. Since hashtable lookups are quite fast, you can simplify array searching by making the data you intend to search through the key of the array, then searching for the data is as simple as $value = isset($foo[$bar])) ? $foo[$bar] : NULL;. This searching mechanism is way faster then manual array iteration, even though having string keys maybe more memory intensive then using simple numeric keys.


15. isset vs in_array 와 array_key_exists

PHP의 일반적인 작업 중 하나라면 배열 검색입니다. 이 과정은 일반적인 배열 검색이나 in_array() 함수, 혹은 수동적으로 구현한 순환 검색기능을 통해 꽤나 느려지게 만듭니다. 만약 당신이 꽤나 큰 배열 통째로 이런 식으로 자주 검사한다면 성능에 꽤나 큰 타격을 입힐겁니다. 그럼 어째야 할까요? 젠드 엔진이 데이터를 저장하는 방식을 빌려서 해결할 수 있습니다. 내부적으로 배열들에 key를  hash table안에 저장 배열 요소(key)는 hash table의 key가 될 수 있습니다.hash table은 값을 찾기 위해 key를 이용하는데요.hashtable은 검색은 꽤 빠른 편이구요, 아마 당신은 의도한대로 key를 통해 데이터를 찾을 수 있을겁니다. 찾는 데이터는 간단하게 말하면  $value = isset($foo[$bar]))?$foo[$bar]:NULL; 과 같이 되는거죠. 이 탐색 메커니즘은 문자열로 된 key가 숫자로 된 key보다 메모리를 많이 먹음에도 불구, 배열 순회를 통해 결과를 얻는 것보다 빠를 겁니다.


view plaincopy to clipboardprint?

$keys = array("apples"=>1, "oranges"=>1, "mangoes"=>1);  

if (isset($keys['mangoes'])) { ... }  

 

// is roughly 3 times faster then  

 

$keys = array("apples", "oranges", "mangoes");  

if (in_array('mangoes', $keys)) { ... }  

 

// isset is also faster then  

if(array_key_exists('mangoes', $keys)) { ... }  

Note: However the lookup times don't diverge until you've got a very considerable amount of data in your array. e.g. If you have just 2-3 entries in your array, it will take more time to hash the values and perform the lookup than it would take to perform a simple linear search ( O( n ) vs. O( log n ) )


참고: 배열이 많은 데이터를 갖고 있다고 해서 배열의 연산량이 발산하진 않습니다. 예를 들자면 배열에 단지 2~3개의 항목이 있을 때,  간단한 선형 탐색이 hash table 검색보다 오래 걸릴겁니다( O(n) vs O(log n) )




16. Free unnecessary memory

Unset your variables to free memory, especially large arrays.


16. 필요없는 메모리를 해제하세요.

메모리 여유를 위해, 필요없는 데이터를 해제하세요. 특히 큰 배열이라면 더욱.


17. Specify full paths

Use full paths in includes and requires, less time spent on resolving the OS paths.

view plaincopy to clipboardprint?

include( '/var/www/html/your_app/database.php' );    

//is better than    

include( 'database.php' );   

Read more...


17. 절대경로로 명명하세요.

require에 절대 경로를 이용하는 것이 상대 경로를 이용하는 것보다 적은 시간을 소요합니다.

18. regex vs. strncasecmp, strpbrk and stripos

See if you can use strncasecmp, strpbrk and stripos instead of regex, since regex is usually slower.


18. regext vs strncasecmp, strpbrk and stripos

가능하다면 정규표현식보다 strncasecmp, strpbrk, stripos을 사용하세요. regex는 보통 느립니다.

19. str_replace vs. preg_replace vs. strtr

The str_replace is better than preg_replace, but strtr is better than str_replace by afactor of 4.


19. str_replace vs preg_replace vs strtr

str_replace함수가 preg_replace 보다 성능이 좋습니다. 그러나 strtr은 str_replace보다 4배 정도 빠릅니다.

20. select vs. multi if and else if statements

It’s better to use select statements than multi if, else if statements.


20. select vs 다중 if - else if 문

select를 쓰는게 다중 if 문을 쓰는 것 보다 낫습니다.

view plaincopy to clipboardprint?

switch( $name )  

 {  

  case 'aaa':  

  // do something  

  break;  

 

  case 'bbb':  

  // do something  

  break;  

 

  case 'ccc':  

  // do something  

  break;  

 

  default:  

  // do something  

  break;  

 }  

 

 // is better than  

 

 if( $name == 'aaa' )  

 {  

  // do something  

 }  

 else if( $name == 'bbb' )  

 {  

  // do something  

 }  

 else if( $name == 'ccc' )  

 {  

  // do something  

 }  

 else  

 {  

  // do something  

 }  

Read more...


21. Error suppression with @ is very slow

view plaincopy to clipboardprint?

$name = isset( $id ) : 'aaa' : NULL;    

//is better than    

$name = @'aaa';   

Read more...

21. @로 에러문을 무시하는건 몹시 느려요.


22. Boolean Inversion

Most of the time, inverting a boolean value is as simple as using the logical ‘not’ operator e.g. false = !true. That’s easy enough, but occasionally you might find yourself working with integer-type booleans instead, with 1s and 0s in the place of true and false; in that case, here’s a short PHP snippet that does the same thing:


22. 불대수 반전

많은 경우에,  불대수의 값을반전할 때 not 연산을 하는 것이 제일 간단하다. 저 방법도 충분히 쉬운데, 때때로 정수값과 불대수를 혼동해서 사용하는 경우가 있을 것이다(1 = true, 0 = false). 이런 경우에, 동일한 역할을 수행하는 php 코드 조각을 제시한다.


view plaincopy to clipboardprint?

$true = 1;  

$false = 1 - $true;  

$true = 1 - $false;  

The same principle can be used any time you want to toggle an integer between two values e.g. between 2 and 5:

위의 원리는 아래의 소스와 동일한 원리이다.

view plaincopy to clipboardprint?

$val = 5;  

$val = 7 - $val; // now it's 2...  

$val = 7 - $val; // and now it's 5 again  


23. isset($var, $var, …)

Useful little thing, this - you can check the state of multiple variables within a single PHP isset() construct, like so:


23. isset($var, $var, …)

제법 유용한 건데, 여러개의 변수를 isset()함수를 통해 한 번에 체크할 수 있다.

view plaincopy to clipboardprint?

$foo = $bar = 'are set';  

isset($foo, $bar); // true  

isset($foo, $bar, $baz); // false  

isset($baz, $foo, $bar); // false  

On a related note, in case you’re not already aware of this, isset actually sees null as being not set:

이것과 관련해서, 당신이 이것을 모를 경우에 대해, isset은 NULL과 할당이 되지 않음을 동일히 본다.

view plaincopy to clipboardprint?

$list = array('foo' => 'set', 'bar' => null);  

isset($list['foo']); // true, as expected  

isset($list['bar']); // false!  

In situations like the above, it’s more reliable to use array_key_exists().

위와 같은 경우에는 array_key_exists()를 사용하는 것이 좀 더 안정적이다.


24. Modulus Operator

During a loop, it’s a fairly common need to perform a specific routine every n-th iteration. The modulus operator is extremely helpful here - it’ll divide the first operand by the second and return the remainder, to create a useful, cyclic sequence:


24. 나머지 연산자.

반복문 구동 중에, 특정한 루틴이 n 번째의 구동 중에 필요할 경우가 종종 있다. 나머지 연산은 이럴 때 굉장히 쓸만하다. -  이건 첫 번째 연산을 나눈 뒤에 나머지를 반환합니다. 반복 구문을 쓸모있게 만들어봅시다.

view plaincopy to clipboardprint?

for ($i = 0; $i < 10; ++$i)  

{  

   echo $i % 4, ' ';  

}  

// outputs 0 1 2 3 0 1 2 3 0 1  


25. http_build_query

This function turns a native array into a nicely-encoded query string. Furthermore, this native function is configurable and fully supports nested arrays.


25. http_build_query

이 함수는 잘 인코딩된 쿼리 스트링을 기본 배열로 돌려줍니다. 게다가, 이 기본 함수는 중첩 배열을 완벽하게 지원합니다.

26. <input name="foo[bar]" />

HTML + PHP are quite capable of handling form fields as arrays. This one’s particularly helpful when dealing with multiple checkboxes since the selected values can be automatically pushed into an indexed (or associative) array, rather than having to capture them yourself.


26. <input name=”foo[bar”] />

HTML + PHP 조합은 배열로 form의 field들을 괜찮게 다룰 수 있습니다. 위와 같이 설정하는 것은 다중 체크박스를 할 때 인덱스(나 연관) 배열로 반환하기 때문에 훨씬 편하게 쓸 수 있습니다.


27. get_browser()

Easily get your hands on the users browser-type. Some leave this process to the browser end but can be useful to get this info server side.


27. get_browser()

손쉽게 유저의 브라우저 타입이 뭔지 알 수 있습니다. 어떤 브라우저는 이 프로세스를 종료할 때 처리하지만, 서버에선 여전히 유용한 정보 획득 수단입니다.

28. debug_print_backtrace()

I use this one a lot, print a debug-style list of what was called to get the the point where this function is called.


28. debug_print_backtrace()

저는 이것을 꽤 많이 사용하는데, 이 함수가 호출된 위치를 디버깅 스타일로 출력해줍니다.


29. Automatic optimization for your database

Just like you need to defrag and check your file system, it’s important to do the same thing with SQL tables. If you don’t, you might end up with slow and corrupted database tables.


Furthermore, you will probably add and delete tables from time to time. Therefore, you want a solution that works no matter how your database looks like. For this, you can use this PHP script that finds all your tables, and then perform Optimize on every single one. Then a good idea can be to do this every night (or whenever your server is least accessed) with “cron” because you don’t want to delay your surfers to much.


29. 데이터베이스 자동 최적화 하기

파일 시스템을 조각 모음하고 체크하는 것을 좋아한다면, 이것은 SQL 테이블에서도 같은 역할을 수행하는 중요한 일입니다. 만약 당신이 그렇지 않다면, 당신의 데이터베이스는 결국 느리고 박살나겠지요.


게다가, 당신이 테이블을 매번 추가하거나, 삭제해서 DB의 모양이 어떻게 되건  당신이 원하는 모양으로 솔루션이 작동되길 바라겠죠.  이것을 위해, 당신은 PHP 스크립트를 이용하여 최적화를 통해 모든 테이블을 찾아가 하나씩 명령을 처리하고 있습니다. 그렇다면 당신이 매일밤 ‘크론’을 통해 수행할 수 있는 좋은 방법이 있습니다. (왜 크론을 쓰냐면 당신을 방해하고 싶지 않아서지요)

view plaincopy to clipboardprint?

dbConnect()  

$tables = mysql_query("SHOW TABLES");  

 

while ($table = mysql_fetch_assoc($tables))  

{  

  foreach ($table as $db => $tablename)  

  {  

      mysql_query("OPTIMIZE TABLE '".$tablename."'")  

          or die(mysql_error());  

  }  

}  



30. require() vs. require_once()

Use require() instead of require_once() where possible.


30. require() vs require_once()

가능하다면 require_once 대신아 require 함수를 사용하세요.


Read more...


31. Check System Calls

A common mistake with Apache


31. 시스템 호출을 확인하세요

보통 아파치에서 가장 많이 하는 실수입니다.

view plaincopy to clipboardprint?

/usr/sbin/apache2 -X &  

strace -p 16367 -o sys1.txt   

grep stat sys1.txt | grep -v fstat | wc -l  

...  

index.html (No such file or directory)  

index.cgi  (No such file or directory)  

index.pl   (No such file or directory)  

index.php ...  

Fix DirectoryIndex

디렉토리 인덱스를 수정하세요.

view plaincopy to clipboardprint?

<Directory /var/www>  

   DirectoryIndex index.php  

</Directory>  


32. Secure HTTP connections

You can force a secure HTTP connection using the following code,

view plaincopy to clipboardprint?

if (!($HTTPS == "on")) {  

  header ("Location: https://$SERVER_NAME$php_SELF");  

  exit;  

}  


33. Avoid magic like __get, __set, __autoload

_get() and __set() will provide a convenience mechanism for us to access the individual entry properties, and proxy to the other getters and setters. They also will help ensure that only properties we whitelist will be available in the object. This obviously carries a small cost. Also, __autoload will affect your code more less in the same way as require_once.


33.  __get, __set, __autoload와 같은 사술을 피하라.

__get() 과 __set()  개별 항목의 속성을 접근하거나, 다른 getter나 setter를 대신하는데 꽤나 편리한 방식을 제공한다. 이것들은 언제나 우리가 이 변수를 사용해도 되는지, 화이트리스트같이 확신을 제공해주기도 합니다. __autoload보다 __get, __set이 적은 비용을 소모하지만, 소모한다는 사실은 붕명하며 당신의 코드에 require_once와 같은 방식으로 적은 영향을 미칠 것입니다.

References

[1] Here it is. 8 randomly useful PHP tricks. http://theresmystuff.com, 2010.


[2] TJS. 5 useful (PHP) tricks and functions you may not know. http://www.tjs.co.uk, 2010.


[3] Checkmate - Play with problems. Optimize your PHP Code - Tips, Tricks and Techniques. http://abcphp.com, 2008.


[4] iBlog - Ilia Alshanetsky. PHP Optimization Tricks. http://ilia.ws, 2004.

Posted by TY
,