10 effective methods to improve C program efficiency _c language

Source: Internet
Author: User
Tags strlen

The beauty of any code lies not only in finding a solution to a given problem, but in its simplicity, effectiveness, compactness and efficiency (memory). Designing code is more difficult than actual execution. Therefore, every programmer should keep these basic things in mind when it is developed in C language.

This article introduces you to the 10 ways to standardize your C code.

1. Avoid unnecessary function calls

Consider the following 2 functions:

Copy Code code as follows:

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]);

}

}


Note that the functions of these two functions are similar. However, the first function calls the strlen () function multiple times, while the second function calls only the function strlen () once. So the first function is significantly better than the second.

2. Avoid unnecessary memory references

This time we use 2 more examples to explain:

Copy Code code as follows:

int multiply (int *num1, int *num2)

{

*NUM1 = *num2;

*num1 + = *num2;

return *NUM1;

}

int multiply1 (int *num1, int *num2)

{

*NUM1 = 2 **num2;

return *NUM1;

}


Similarly, these two functions have similar functionality. The difference is that there are 5 memory references in the first function (1 for reading *NUM1, 2 for reading *num2 and 2 for writing to *NUM1), while the second function is only 2 memory references (one for Readin G *num2 and one for writing to *NUM1). Which one do you think is better now?

3. Save memory (the concept of memory alignment and filling)

Copy Code code as follows:

struct {

char c;

int i;

Short S;

}str_1;

struct {

char c;

Short S;

int i;

}str_2;


Assuming that a character requires 1 bytes, short occupies 2 bytes and an int requires 4 bytes of memory. At first, we would assume that the structure defined above is the same and therefore occupy the same amount of memory. However, while str_1 occupies 12 bytes, the second structure requires only 8 bytes? How is that possible?

Note that in the first structure, 3 different 4 bytes are assigned to three data types, while in the first 4 of the second structure char and short can be adopted, int can be adopted at the second 4 byte boundary (altogether 8 bytes).

4. Use unsigned integers instead of integers, if you know the values will always be negative.

Some processors can handle unsigned integers faster than signed integers. (This is also a good practice to help self-documenting code).

5. Constant items are always on the left in a logical conditional statement.

Copy Code code as follows:

int x = 4;

if (x = 1) {

xx = x+ 2;

printf ("%d", x); Output is 3

}

int x = 4;

if (1 = x) {

xx = x+ 2;

printf ("%d", x); Compilation error

}


Use the ' = ' assignment operator to override the ' = = ' equality operator, which is a common input error. Constant entries on the left will produce a compile-time error that allows you to easily catch your errors. Note: "=" is an assignment operator. b = 1 Sets the variable b equal to the value 1. ' = = ' equality operator. Returns True if the left is equal to the right, otherwise false.

6. Use a typedef instead of macro where possible. Of course sometimes you can't avoid macro, but the TypeDef is better.

Copy Code code as follows:

typedef int* INT_PTR;

INT_PTR A, B;

# define INT_PTR int*;

INT_PTR A, B;


In this macro definition, A is a pointer to an integer, and b is only an integer declaration. Use both typedef A and B as pointers to integers.

7. Make sure that the declaration and definition are static unless you want to call the function from a different file.

It is called a static function when the same file function is visible to other functions. It restricts other access to internal functions if we want to hide the function from the outside world. Now we do not need to create a header file for the intrinsic function, and others do not see the function.

The advantages of statically declaring a function include:

A) two or more static functions with the same name can be used in different files.

B the compilation consumes less because there is no external symbolic processing.

Let's do a better understanding of the following examples:

Copy Code code as follows:

/*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 isn't a valid function call as the function Foo can only be called by any other function within first_file.c wher e it is defined.

return 0;

}


8. Use memoization to avoid recursive recurrence

Consider the Fibonacci (Fibonacci) problem; The Fibonacci problem is that it can be solved by a simple recursive method:

Copy Code code as follows:

int fib (n)

{

if (n = = 0 N = = 1) {

return 1;

}

else {

return fib (n-2) + fib (n-1);

}
}


Note: Here we consider the Fibonacci series starting from 1, so the series looks: 1,1,2,3,5,8, ...

Note: From the recursive tree, we compute the FIB (3) function 2 times, FIB (2) function 3 times. This is a duplicate calculation of the same function. If n is very large, the fib<n (i) function grows i<n. A quick way to solve this problem would be to compute the function 1 times, store it in some places, and compute it as needed, rather than repeating it all the time.

This simple technique, called memoization, can be used in recursion, which strengthens the computational speed.

The code for the Fibonacci function memoization should be the following:

Copy Code code as follows:

int calc_fib (int n)

{

int val[n], I;

for (i = 0; I <=n; i++) {

val[i] =-1; Value of the ' the ' of the ' 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
}


Here the CALC_FIB (n) function is called by Main ().

9. Avoid dangling pointers and wild pointers

A pointer to an object has been deleted, then it becomes a dangling pointer. Wild pointers are those uninitialized pointers, and note that the wild pointer does not point to any particular memory location.

Copy Code code as follows:

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);

}


When confronted with these pointers, the program is usually "weird" performance.

10. Always remember to release any memory you assign to the program. The above example is if you release the DP pointer (we use the malloc () function call).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.