讓C程序更高效的10種方法
代碼之美,不僅在于為一個(gè)給定問題找到解決方案,而且還在代碼的簡(jiǎn)單性、有效性、緊湊性和效率(內(nèi)存)。代碼設(shè)計(jì)比實(shí)際執(zhí)行更難 。因此,每一個(gè)程序員當(dāng)用C語言編程時(shí),都應(yīng)該記著這些東西。本文向你介紹規(guī)范你的C代碼的10種方法。
0. 避免不必要的函數(shù)調(diào)用
考慮下面的2個(gè)函數(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;">
- 請(qǐng)注意 這兩個(gè)函數(shù)的功能相似。然而,***個(gè)函數(shù)調(diào)用strlen()函數(shù)多次,而第二個(gè)函數(shù)只調(diào)用函數(shù)strlen()一次。因此***個(gè)函數(shù)性能明顯比第二個(gè)好。
- </span>
- <span style="color: red;">
- <strong>(更新:原作者應(yīng)該是筆誤,把***個(gè)函數(shù)寫成優(yōu)于第二個(gè),否則自相矛盾。)</strong>
- </span>
1、避免不必要的內(nèi)存引用
這次我們?cè)儆?個(gè)例子來對(duì)比解釋:
- 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;">
- 同樣,這兩個(gè)函數(shù)具有類似的功能。所不同的是在***個(gè)函數(shù)( 1 for reading *num1 ,
- 2 for reading *num2 and 2 for writing to *num1)有5個(gè)內(nèi)存的引用,而在第二個(gè)函數(shù)是只有2個(gè)內(nèi)存引用(one for reading *num2 and one for writing to *num1)。
- 現(xiàn)在你認(rèn)為哪一個(gè)好些?
- </span>
2、節(jié)約內(nèi)存(內(nèi)存對(duì)齊和填充的概念)
- struct {
- char c;
- int i;
- short s;
- }str_1;
- struct {
- char c;
- short s;
- int i;
- }str_2;
假設(shè)一個(gè)字符需要1個(gè)字節(jié),short占用2個(gè)字節(jié)和int需要4字節(jié)的內(nèi)存。起初,我們會(huì)認(rèn)為上面定義的結(jié)構(gòu)是相同的,因此占據(jù)相同數(shù)量的內(nèi)存。然而,而str_1占用12個(gè)字節(jié),第二個(gè)結(jié)構(gòu)只需要8個(gè)字節(jié)?這怎么可能呢?
請(qǐng)注意,在***個(gè)結(jié)構(gòu),3個(gè)不同的4個(gè)字節(jié)被分配到三種數(shù)據(jù)類型,而在第二個(gè)結(jié)構(gòu)的前4個(gè)自己char和short可以被采用,int可以采納在第二個(gè)的4個(gè)字節(jié)邊界(一共8個(gè)字節(jié))。
3、使用無符號(hào)整數(shù),而不是整數(shù)的,如果你知道的值將永遠(yuǎn)是否定的。
有些處理器可以處理無符號(hào)的整數(shù)比有符號(hào)整數(shù)的運(yùn)算速度要快。(這也是很好的實(shí)踐,幫助self-documenting代碼)。
#p#
4、在一個(gè)邏輯條件語句中常數(shù)項(xiàng)永遠(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
- }
使用“=”賦值運(yùn)算符,替代“==”相等運(yùn)算符,這是個(gè)常見的輸入錯(cuò)誤。 常數(shù)項(xiàng)放在左側(cè),將產(chǎn)生一個(gè)編譯時(shí)錯(cuò)誤,讓你輕松捕獲你的錯(cuò)誤。注:“=”是賦值運(yùn)算符。 b = 1會(huì)設(shè)置變量b等于值1。 “==”相等運(yùn)算符。如果左側(cè)等于右側(cè),返回true,否則返回false。
5、在可能的情況下使用typedef替代macro。當(dāng)然有時(shí)候你無法避免macro,但是typedef更好。
- typedef int* INT_PTR;
- INT_PTR a , b;
- # define INT_PTR int*;
- INT_PTR a , b;
在這個(gè)宏定義中,a是一個(gè)指向整數(shù)的指針,而b是只有一個(gè)整數(shù)聲明。使用typedef a和b都是 整數(shù)的指針。
6、確保聲明和定義是靜態(tài)的,除非您希望從不同的文件中調(diào)用該函數(shù)。
在同一文件函數(shù)對(duì)其他函數(shù)可見,才稱之為靜態(tài)函數(shù)。它限制其他訪問內(nèi)部函數(shù),如果我們希望從外界隱藏該函數(shù)?,F(xiàn)在我們并不需要為內(nèi)部函數(shù)創(chuàng)建頭文件,其他看不到該函數(shù)。
靜態(tài)聲明一個(gè)函數(shù)的優(yōu)點(diǎn)包括:
- 兩個(gè)或兩個(gè)以上具有相同名稱的靜態(tài)函數(shù),可用于在不同的文件。
- 編譯消耗減少,因?yàn)闆]有外部符號(hào)處理。
讓我們做更好的理解,下面的例子:
- /*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ù)計(jì)算</strong>
考慮Fibonacci(斐波那契)問題;
Fibonacci問題是可以通過簡(jiǎn)單的遞歸方法來解決:
- 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>
注意:從遞歸樹,我們計(jì)算fib(3)函數(shù)2次,fib(2)函數(shù)3次。這是相同函數(shù)的重復(fù)計(jì)算。如果n非常大,fib
這個(gè)簡(jiǎn)單的技術(shù)叫做Memoization,可以被用在遞歸,加強(qiáng)計(jì)算速度。
fibonacci 函數(shù)Memoization的代碼,應(yīng)該是下面的這個(gè)樣子:
- 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、避免懸空指針和野指針
一個(gè)指針的指向?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/