讓C程序更高效的10種方法
代碼之美,不僅在於為一個給定問題找到解決方案,而且還在代碼的簡單性、有效性、緊湊性和效率(內存)。代碼設計比實際執行更難 。因此,每一個程序員當用C語言編程時,都應該記著這些東西。本文向你介紹規範你的C代碼的10種方法。
0. 避免不必要的函數調用
考慮下麵的2個函數:
- 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;">
- 請注意 這兩個函數的功能相似。然而,第一個函數調用strlen()函數多次,而第二個函數隻調用函數strlen()一次。因此第一個函數性能明顯比第二個好。
- </span>
- <span style="color: red;">
- <strong>(更新:原作者應該是筆誤,把第一個函數寫成優於第二個,否則自相矛盾。)</strong>
- </span>
1、避免不必要的內存引用
這次我們再用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;">
- 同樣,這兩個函數具有類似的功能。所不同的是在第一個函數( 1 for reading *num1 ,
- 2 for reading *num2 and 2 for writing to *num1)有5個內存的引用,而在第二個函數是隻有2個內存引用(one for reading *num2 and one for writing to *num1)。
- 現在你認為哪一個好些?
- </span>
2、節約內存(內存對齊和填充的概念)
- struct {
- char c;
- int i;
- short s;
- }str_1;
- struct {
- char c;
- short s;
- int i;
- }str_2;
假設一個字符需要1個字節,short占用2個字節和int需要4字節的內存。起初,我們會認為上麵定義的結構是相同的,因此占據相同數量的內存。然而,而str_1占用12個字節,第二個結構隻需要8個字節?這怎麼可能呢?
請注意,在第一個結構,3個不同的4個字節被分配到三種數據類型,而在第二個結構的前4個自己char和short可以被采用,int可以采納在第二個的4個字節邊界(一共8個字節)。
3、使用無符號整數,而不是整數的,如果你知道的值將永遠是否定的。
有些處理器可以處理無符號的整數比有符號整數的運算速度要快。(這也是很好的實踐,幫助self-documenting代碼)。
4、在一個邏輯條件語句中常數項永遠在左側。
- 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
- }
使用“=”賦值運算符,替代“==”相等運算符,這是個常見的輸入錯誤。 常數項放在左側,將產生一個編譯時錯誤,讓你輕鬆捕獲你的錯誤。注:“=”是賦值運算符。 b = 1會設置變量b等於值1。 “==”相等運算符。如果左側等於右側,返回true,否則返回false。
5、在可能的情況下使用typedef替代macro。當然有時候你無法避免macro,但是typedef更好。
- typedef int* INT_PTR;
- INT_PTR a , b;
- # define INT_PTR int*;
- INT_PTR a , b;
在這個宏定義中,a是一個指向整數的指針,而b是隻有一個整數聲明。使用typedef a和b都是 整數的指針。
6、確保聲明和定義是靜態的,除非您希望從不同的文件中調用該函數。
在同一文件函數對其他函數可見,才稱之為靜態函數。它限製其他訪問內部函數,如果我們希望從外界隱藏該函數。現在我們並不需要為內部函數創建頭文件,其他看不到該函數。
靜態聲明一個函數的優點包括:
- 兩個或兩個以上具有相同名稱的靜態函數,可用於在不同的文件。
- 編譯消耗減少,因為沒有外部符號處理。
讓我們做更好的理解,下麵的例子:
- /*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,以避免遞歸重複計算</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="https://www.fortystones.com/wp-content/uploads/2011/08/fibonacci-recursion-tree.png">
- <img class="aligncenter" title="fibonacci-recursion-tree"
- 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的代碼,應該是下麵的這個樣子:
- 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 )函數被main()調用。</span>
8、避免懸空指針和野指針
一個指針的指向對象已被刪除,那麼就成了懸空指針。野指針是那些未初始化的指針,需要注意的是野指針不指向任何特定的內存位置。
- 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;">
- 當遭遇這些指針,程序通常是”怪異“的表現。</span>
9、 永遠記住釋放你分配給程序的任何內存。上麵的例子就是如果釋放dp指針(我們使用malloc()函數調用)。
最後更新:2017-04-03 16:48:43