閱讀401 返回首頁    go 阿裏雲 go 技術社區[雲棲]


讓C程序更高效的10種方法

代碼之美,不僅在於為一個給定問題找到解決方案,而且還在代碼的簡單性、有效性、緊湊性和效率(內存)。代碼設計比實際執行更難 。因此,每一個程序員當用C語言編程時,都應該記著這些東西。本文向你介紹規範你的C代碼的10種方法。

0. 避免不必要的函數調用

考慮下麵的2個函數:


  1. void str_print( char *str ) 
  2.   
  3.   
  4.     int i; 
  5.   
  6.     for ( i = 0; i < strlen ( str ); i++ ) { 
  7.   
  8.         printf("%c",str[ i ] ); 
  9.   
  10.     } 
  11.   
  12. void str_print1 ( char *str ) 
  13.   
  14.   
  15.     int len; 
  16.   
  17.     len = strlen ( str ); 
  18.   
  19.     for ( i = 0; i < len; i++ ) { 
  20.   
  21.         printf("%c",str[ i ] ); 
  22.   
  23.     } 
  24.   
  25. }

  1. <​span class="Apple-style-span" 
  2. style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
  3. 請注意 這兩個函數的功能相似。然而,第一個函數調用strlen()函數多次,而第二個函數隻調用函數strlen()一次。因此第一個函數性能明顯比第二個好。
  4. </span>
  5. <span style="color: red;">
  6. <strong>(更新:原作者應該是筆誤,把第一個函數寫成優於第二個,否則自相矛盾。)</strong>
  7. </span> 

1、避免不必要的內存引用

這次我們再用2個例子來對比解釋:


  1. int multiply ( int *num1 , int *num2 ) 
  2.   
  3.   
  4.     *num1 = *num2; 
  5.   
  6.     *num1 += *num2; 
  7.   
  8.     return *num1; 
  9.   
  10. int multiply1 ( int *num1 , int *num2 ) 
  11.   
  12.   
  13.     *num1 = 2 * *num2; 
  14.   
  15.     return *num1; 
  16.   

  1. <span class="Apple-style-span" 
  2. style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
  3. 同樣,這兩個函數具有類似的功能。所不同的是在第一個函數( 1 for reading *num1 , 
  4. for reading *num2 and 2 for writing to *num1)有5個內存的引用,而在第二個函數是隻有2個內存引用(one for reading *num2 and one for writing to *num1)。
  5. 現在你認為哪一個好些?
  6. </span> 

2、節約內存(內存對齊和填充的概念)


  1. struct { 
  2.   
  3.     char c; 
  4.   
  5.     int i; 
  6.   
  7.     short s; 
  8.   
  9. }str_1; 
  10. struct { 
  11.   
  12.     char c; 
  13.   
  14.     short s; 
  15.   
  16.     int i; 
  17.   
  18. }str_2; 

假設一個字符需要1個字節,short占用2個字節和int需要4字節的內存。起初,我們會認為上麵定義的結構是相同的,因此占據相同數量的內存。然而,而str_1占用12個字節,第二個結構隻需要8個字節?這怎麼可能呢?

請注意,在第一個結構,3個不同的4個字節被分配到三種數據類型,而在第二個結構的前4個自己char和short可以被采用,int可以采納在第二個的4個字節邊界(一共8個字節)。

3、使用無符號整數,而不是整數的,如果你知道的值將永遠是否定的。

有些處理器可以處理無符號的整數比有符號整數的運算速度要快。(這也是很好的實踐,幫助self-documenting代碼)。

4、在一個邏輯條件語句中常數項永遠在左側。


  1. int x = 4; 
  2.   
  3. if ( x = 1 ) { 
  4.   
  5.     x = x + 2; 
  6.   
  7.     printf("%d",x);          // Output is 3 
  8.   
  9. int x = 4; 
  10.   
  11. if ( 1 = x ) { 
  12.   
  13.     x = x + 2; 
  14.   
  15.     printf("%d",x);   // Compilation error 
  16.   

使用“=”賦值運算符,替代“==”相等運算符,這是個常見的輸入錯誤。 常數項放在左側,將產生一個編譯時錯誤,讓你輕鬆捕獲你的錯誤。注:“=”是賦值運算符。 b = 1會設置變量b等於值1。 “==”相等運算符。如果左側等於右側,返回true,否則返回false。

5、在可能的情況下使用typedef替代macro。當然有時候你無法避免macro,但是typedef更好。


  1. typedef intINT_PTR
  2.   
  3. INT_PTR a , b; 
  4.   
  5. # define INT_PTR int*; 
  6.   
  7. INT_PTR a , b; 

在這個宏定義中,a是一個指向整數的指針,而b是隻有一個整數聲明。使用typedef a和b都是 整數的指針。

6、確保聲明和定義是靜態的,除非您希望從不同的文件中調用該函數。

在同一文件函數對其他函數可見,才稱之為靜態函數。它限製其他訪問內部函數,如果我們希望從外界隱藏該函數。現在我們並不需要為內部函數創建頭文件,其他看不到該函數。

靜態聲明一個函數的優點包括:

  1. 兩個或兩個以上具有相同名稱的靜態函數,可用於在不同的文件。
  2. 編譯消耗減少,因為沒有外部符號處理。

讓我們做更好的理解,下麵的例子:


  1. /*first_file.c*/ 
  2.   
  3. static int foo ( int a ) 
  4.   
  5.   
  6. /*Whatever you want to in the function*/ 
  7.   
  8.   
  9. /*second_file.c*/ 
  10.   
  11. int foo ( int ) 
  12.   
  13. int main() 
  14.   
  15.   
  16.     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. 
  17.   
  18.     return 0; 
  19.   
  20. }

  1. <strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;"> </strong>

  1. <strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">7、使用Memoization,以避免遞歸重複計算</strong> 

考慮Fibonacci(斐波那契)問題;

Fibonacci問題是可以通過簡單的遞歸方法來解決:


  1. int fib ( n ) 
  2.   
  3.   
  4.     if ( n == 0 || n == 1 ) { 
  5.   
  6.         return 1; 
  7.   
  8.     } 
  9.   
  10.     else { 
  11.   
  12.         return fib( n - 2 ) + fib ( n - 1 ); 
  13.   
  14.     } 
  15.   
  16. }

  1. <span class="Apple-style-span" 
  2. style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
  3. 注:在這裏,我們考慮Fibonacci 係列從1開始,因此,該係列看起來:1,1,2,3,5,8,...</span> 

  1. <span class="Apple-style-span" 
  2. style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
  3. <a href="https://www.fortystones.com/wp-content/uploads/2011/08/fibonacci-recursion-tree.png">
  4. <img class="aligncenter" title="fibonacci-recursion-tree" 
  5. src="https://www.fortystones.com/wp-content/uploads/2011/08/fibonacci-recursion-tree-300x174.png" alt="" width="300" height="174" /></a> </span> 

注意:從遞歸樹,我們計算fib(3)函數2次,fib(2)函數3次。這是相同函數的重複計算。如果n非常大,fib

這個簡單的技術叫做Memoization,可以被用在遞歸,加強計算速度。

fibonacci 函數Memoization的代碼,應該是下麵的這個樣子:


  1. int calc_fib ( int n ) 
  2.   
  3.   
  4.     int val[ n ] , i; 
  5.   
  6.     for ( i = 0; i <=n; i++ ) { 
  7.   
  8.         val[ i ] = -1;      // Value of the first n + 1 terms of the fibonacci terms set to -1 
  9.   
  10.     } 
  11.   
  12.     val[ 0 ] = 1;               // Value of fib ( 0 ) is set to 1 
  13.   
  14.     val[ 1 ] = 1;           // Value of fib ( 1 ) is set to 1 
  15.   
  16.     return fib( n , val ); 
  17.   
  18.   
  19. int fib( int n , int* value ) 
  20.   
  21.   
  22.     if ( value[ n ] != -1 ) { 
  23.   
  24.         return value[ n ];              // Using memoization 
  25.   
  26.     } 
  27.   
  28.     else { 
  29.   
  30.         value[ n ] = fib( n - 2 , value ) + fib ( n - 1 , value );          // Computing the fibonacci term 
  31.   
  32.     } 
  33.   
  34.     return value[ n ];                // Returning the value 
  35.   
  36. }

  1. <span class="Apple-style-span" 
  2. style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
  3. 這裏calc_fib( n )函數被main()調用。</span> 

8、避免懸空指針和野指針

一個指針的指向對象已被刪除,那麼就成了懸空指針。野指針是那些未初始化的指針,需要注意的是野指針不指向任何特定的內存位置。


  1. void dangling_example() 
  2.   
  3.   
  4.     int *dp = malloc ( sizeof ( int )); 
  5.   
  6.     /*........*/ 
  7.   
  8.     free( dp );             // dp is now a dangling pointer 
  9.   
  10.     dp = NULL;      // dp is no longer a dangling pointer 
  11.   
  12.   
  13. void wild_example() 
  14.   
  15.   
  16.     int *ptr;       // Uninitialized pointer 
  17.   
  18.     printf("%u"\n",ptr ); 
  19.   
  20.     printf("%d",*ptr ); 
  21.   
  22. }

  1. <span class="Apple-style-span" 
  2. style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
  3. 當遭遇這些指針,程序通常是”怪異“的表現。</span> 

9、 永遠記住釋放你分配給程序的任何內存。上麵的例子就是如果釋放dp指針(我們使用malloc()函數調用)。


最後更新:2017-04-03 16:48:43

  上一篇:go ZOJ 2107 HDU 1007 最近點對
  下一篇:go 微軟將Bing變開放平台 同穀歌爭奪開發者