function performance

What about this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
int any(char *s1, char *s2) 
{
        char array[256]; 

        int  i;

        if (s1 == NULL) {

                if (s2 == NULL) {

                        return(0);

                } else {

                        return(-1);

                }

        }

        for(i = 0; i < 256; i++) {

                array[i] = 0;

        }

        while(*s2 != '\0') {

                array[*s2] = 1;

                s2++;

        }

        i = 0;

        while(s1[i] != '\0') {

                if (array[s1[i]] == 1) {

                        return(i);

                }

                i++;
        }

        return(-1);
}


makes it perform better than this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int any(char s1[], char s2[])
{
  int i;
  int j;
  int pos;

  pos = -1;

  for(i = 0; pos == -1 && s1[i] != '\0'; i++)

  {

    for(j = 0; pos == -1 && s2[j] != '\0'; j++)

    {

      if(s2[j] == s1[i])

      {

        pos = i;

      }
    } 
  }

  return pos;
} 


?
Last edited on
How well each perform will depend on the strings passed in.

The first one has 3 loops:
- length 256
- length M (length of s1 string)
- length N (length of s2 string)

Therefore it will have 256+N+M iterations



The second one has 2 nested loops:
- length M
- length N

Since the loops are nested, it will have N*M iterations.



Whether or not 256+N+M performs better than N*M depends on the values of N and M.
Topic archived. No new replies allowed.