讓C程序更高效的10種方法
代碼之美,不僅在于為一個給定問題找到解決方案,而且還在代碼的簡單性、有效性、緊湊性和效率(內(nèi)存)。代碼設(shè)計比實際執(zhí)行更難 。因此,每一個程序員當(dāng)用C語言編程時,都應(yīng)該記著這些東西。本文向你介紹規(guī)范你的C代碼的10種方法。
0. 避免不必要的函數(shù)調(diào)用
考慮下面的2個函數(shù):
- void str_print( char *str )
- {
- int i;
- for ( i = 0; i < strlen ( str ); i++ ) {
- printf("%c",str[ i ] );
- }
- }
- void str_print1 ( char *str )
- {
- int len;
- len = strlen ( str );
- for ( i = 0; i < len; i++ ) {
- printf("%c",str[ i ] );
- }
- }
- <span class="Apple-style-span"
- style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
- 請注意 這兩個函數(shù)的功能相似。然而,***個函數(shù)調(diào)用strlen()函數(shù)多次,而第二個函數(shù)只調(diào)用函數(shù)strlen()一次。因此***個函數(shù)性能明顯比第二個好。
- </span>
- <span style="color: red;">
- <strong>(更新:原作者應(yīng)該是筆誤,把***個函數(shù)寫成優(yōu)于第二個,否則自相矛盾。)</strong>
- </span>
1、避免不必要的內(nèi)存引用
這次我們再用2個例子來對比解釋:
- int multiply ( int *num1 , int *num2 )
- {
- *num1 = *num2;
- *num1 += *num2;
- return *num1;
- }
- int multiply1 ( int *num1 , int *num2 )
- {
- *num1 = 2 * *num2;
- return *num1;
- }
- <span class="Apple-style-span"
- style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
- 同樣,這兩個函數(shù)具有類似的功能。所不同的是在***個函數(shù)( 1 for reading *num1 ,
- 2 for reading *num2 and 2 for writing to *num1)有5個內(nèi)存的引用,而在第二個函數(shù)是只有2個內(nèi)存引用(one for reading *num2 and one for writing to *num1)。
- 現(xiàn)在你認(rèn)為哪一個好些?
- </span>
2、節(jié)約內(nèi)存(內(nèi)存對齊和填充的概念)
- struct {
- char c;
- int i;
- short s;
- }str_1;
- struct {
- char c;
- short s;
- int i;
- }str_2;
假設(shè)一個字符需要1個字節(jié),short占用2個字節(jié)和int需要4字節(jié)的內(nèi)存。起初,我們會認(rèn)為上面定義的結(jié)構(gòu)是相同的,因此占據(jù)相同數(shù)量的內(nèi)存。然而,而str_1占用12個字節(jié),第二個結(jié)構(gòu)只需要8個字節(jié)?這怎么可能呢?
請注意,在***個結(jié)構(gòu),3個不同的4個字節(jié)被分配到三種數(shù)據(jù)類型,而在第二個結(jié)構(gòu)的前4個自己char和short可以被采用,int可以采納在第二個的4個字節(jié)邊界(一共8個字節(jié))。
3、使用無符號整數(shù),而不是整數(shù)的,如果你知道的值將永遠(yuǎn)是否定的。
有些處理器可以處理無符號的整數(shù)比有符號整數(shù)的運算速度要快。(這也是很好的實踐,幫助self-documenting代碼)。
#p#
4、在一個邏輯條件語句中常數(shù)項永遠(yuǎn)在左側(cè)。
- int x = 4;
- if ( x = 1 ) {
- x = x + 2;
- printf("%d",x); // Output is 3
- }
- int x = 4;
- if ( 1 = x ) {
- x = x + 2;
- printf("%d",x); // Compilation error
- }
使用“=”賦值運算符,替代“==”相等運算符,這是個常見的輸入錯誤。 常數(shù)項放在左側(cè),將產(chǎn)生一個編譯時錯誤,讓你輕松捕獲你的錯誤。注:“=”是賦值運算符。 b = 1會設(shè)置變量b等于值1。 “==”相等運算符。如果左側(cè)等于右側(cè),返回true,否則返回false。
5、在可能的情況下使用typedef替代macro。當(dāng)然有時候你無法避免macro,但是typedef更好。
- typedef int* INT_PTR;
- INT_PTR a , b;
- # define INT_PTR int*;
- INT_PTR a , b;
在這個宏定義中,a是一個指向整數(shù)的指針,而b是只有一個整數(shù)聲明。使用typedef a和b都是 整數(shù)的指針。
6、確保聲明和定義是靜態(tài)的,除非您希望從不同的文件中調(diào)用該函數(shù)。
在同一文件函數(shù)對其他函數(shù)可見,才稱之為靜態(tài)函數(shù)。它限制其他訪問內(nèi)部函數(shù),如果我們希望從外界隱藏該函數(shù)?,F(xiàn)在我們并不需要為內(nèi)部函數(shù)創(chuàng)建頭文件,其他看不到該函數(shù)。
靜態(tài)聲明一個函數(shù)的優(yōu)點包括:
- 兩個或兩個以上具有相同名稱的靜態(tài)函數(shù),可用于在不同的文件。
- 編譯消耗減少,因為沒有外部符號處理。
讓我們做更好的理解,下面的例子:
- /*first_file.c*/
- static int foo ( int a )
- {
- /*Whatever you want to in the function*/
- }
- /*second_file.c*/
- int foo ( int )
- int main()
- {
- foo(); // This is not a valid function call as the function foo can only be called by any other function within first_file.c where it is defined.
- return 0;
- }
- <strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;"> </strong>
- <strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">7、使用Memoization,以避免遞歸重復(fù)計算</strong>
考慮Fibonacci(斐波那契)問題;
Fibonacci問題是可以通過簡單的遞歸方法來解決:
- int fib ( n )
- {
- if ( n == 0 || n == 1 ) {
- return 1;
- }
- else {
- return fib( n - 2 ) + fib ( n - 1 );
- }
- }
- <span class="Apple-style-span"
- style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
- 注:在這里,我們考慮Fibonacci 系列從1開始,因此,該系列看起來:1,1,2,3,5,8,...</span>
- <span class="Apple-style-span"
- style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
- <a href="http://www.fortystones.com/wp-content/uploads/2011/08/fibonacci-recursion-tree.png">
- <img class="aligncenter" title="fibonacci-recursion-tree"
- src="http://www.fortystones.com/wp-content/uploads/2011/08/fibonacci-recursion-tree-300x174.png" alt="" width="300" height="174" /></a> </span>
注意:從遞歸樹,我們計算fib(3)函數(shù)2次,fib(2)函數(shù)3次。這是相同函數(shù)的重復(fù)計算。如果n非常大,fib
這個簡單的技術(shù)叫做Memoization,可以被用在遞歸,加強(qiáng)計算速度。
fibonacci 函數(shù)Memoization的代碼,應(yīng)該是下面的這個樣子:
- int calc_fib ( int n )
- {
- int val[ n ] , i;
- for ( i = 0; i <=n; i++ ) {
- val[ i ] = -1; // Value of the first n + 1 terms of the fibonacci terms set to -1
- }
- val[ 0 ] = 1; // Value of fib ( 0 ) is set to 1
- val[ 1 ] = 1; // Value of fib ( 1 ) is set to 1
- return fib( n , val );
- }
- int fib( int n , int* value )
- {
- if ( value[ n ] != -1 ) {
- return value[ n ]; // Using memoization
- }
- else {
- value[ n ] = fib( n - 2 , value ) + fib ( n - 1 , value ); // Computing the fibonacci term
- }
- return value[ n ]; // Returning the value
- }
- <span class="Apple-style-span"
- style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
- 這里calc_fib( n )函數(shù)被main()調(diào)用。</span>
#p#
8、避免懸空指針和野指針
一個指針的指向?qū)ο笠驯粍h除,那么就成了懸空指針。野指針是那些未初始化的指針,需要注意的是野指針不指向任何特定的內(nèi)存位置。
- void dangling_example()
- {
- int *dp = malloc ( sizeof ( int ));
- /*........*/
- free( dp ); // dp is now a dangling pointer
- dp = NULL; // dp is no longer a dangling pointer
- }
- void wild_example()
- {
- int *ptr; // Uninitialized pointer
- printf("%u"\n",ptr );
- printf("%d",*ptr );
- }
- <span class="Apple-style-span"
- style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
- 當(dāng)遭遇這些指針,程序通常是”怪異“的表現(xiàn)。</span>
9、 永遠(yuǎn)記住釋放你分配給程序的任何內(nèi)存。上面的例子就是如果釋放dp指針(我們使用malloc()函數(shù)調(diào)用)。
原文鏈接:http://www.fortystones.com/tips-to-make-c-program-effective/























