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.