Optimizing Program Performance-Eliminating Loop Inefficiencies

Source: Internet
Author: User

See the following two functions:

1/* Convert string to lower case: slow */
2 voidLower1
(Char * s)
3 {
4 int I;
5
6 for (I = 0; I <strlen (s );
I ++)
7 if (s [I]> = 'A' & s [I] <= 'Z ')
8 s [I]-= ('A'-'A ');
9}
10
11/* Convert string to lower case: faster */
12 voidLower2
(Char * s)
13 {
14 int I;
15 int len = strlen (s );

16
17 for (I = 0; I <len
; I ++)
18 if (s [I]> = 'A' & s [I] <= 'Z ')
19 s [I]-= ('A'-'A ');
20}
21
22/* Implementation of library function strlen */
23/* Compute length of string */
24 size_t strlen (const char * s)
25 {
26 int length = 0;
27 while (* s! = '/0 '){
28 s ++;
29 length ++;
30}
31 return length;
32}

 

 

The functions of lower1 and lower2 are the same. They convert character strings into lowercase letters. And it looks almost the same.

However, the difference is that in the for loop, lower1 calls strlen each time, But lower2 does not.

 

This alone leads to a huge difference in performance.

Lower1 grows by Square

Lower2 increases linearly.

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.