在C語言中,不少人會利用#define的方式來宣告字串常數(String Constant)。舉個例子:

#define strConst "A string constant"
        .
        .
        .
    printf( "string: %s\n", strConst );
        .
        .
        .
    sptr = strConst;
        .
        .
        .
    result = strcmp( s, strConst );

實際上,C預置處理器(C Preprocessor)會將程式碼中所有strConst取代成"A string constant".

        .
        .
        .
    printf( "string: %s\n", "A string constant" );
        .
        .
        .
    sptr = "A string constant";
        .
        .
        .
    result = strcmp( s, "A string constant" );

而問題來了,同樣的字串常數在程式碼中會多次的出現。優化的編譯器會將字串常數放置在記憶體空間,並且以「指標」的方式來取代「字串」,而非優化的編譯器或許會將三份相同的字串常數各別放置到記憶體中,導致浪漫了記憶體的空間。

優化DIY

1) 建立一個字元的陣列

2) 以字串的位址做初始化

char strconst[] = "A String Constant";
        .
        .
        .
    sptr = strconst; // Rather than sptr = "A String Constant"
        .
        .
        .
    printf( strconst ); // Rather than printf( "A String Constant" );
        .
        .
        .

    // Rather than strcmp( someString, "A String Constant"):

    if( strcmp( someString, strconst ) == 0 ) {
        .
        .
        .
    }

This code will maintain only a single copy of the string literal constant in memory, even if the compiler doesn't directly support the string optimization. Even if your compiler directly supports this optimization, there are several good reasons why you should use this trick rather than relying on your compiler's optimization facilities to do the work for you.

.In the future you might have to port your code to a different compiler that doesn't support this optimization.

.By handling the optimization manually, you don't have to worry about it.

.By using a pointer variable rather than a string literal constant, you have the option of easily changing the string whose address this pointer contains under program control

.In the future you might want to modify the program to switch (natural) languages under program control

整理至《Write Great Code, Volume 2»7.8. String Constants

創作者介紹
創作者 硬幫邦 的頭像
coolfox

硬幫邦

coolfox 發表在 痞客邦 留言(0) 人氣( 4921 )