简体   繁体   中英

Performace of character array is better than strings?

I was solving a question and was getting constant TLE's, then I searched for the solution online and found the exact code was working flawlessy except there was one difference and that was char array and strings.

Looked up about the performance difference of these two DS but couldn't find anything that of that help.

Char array gives a time of 31ms on an online judge. Meanwhile the string one gives a TLE(2000ms). The maximum characters inputted are of size 131072.

Code snippet of char array:

char s[131073];
int getScore(int l, int r,char curr)
{
    int score = 0;
    for(int i=l; i<r; i++)
        if(s[i]!=curr)
            score++;
        
    return score;
}
 
int dnc(int left, int right, char curr)
{
    if(left == right) return 0;
    if(right == left+1) return s[left]==curr ? 0 : 1;
    int mid = (left+right)/2; 
 
    return min(getScore(left,mid,curr) + dnc(mid,right,curr+1),getScore(mid,right,curr) + dnc(left,mid,curr+1));
}

String code:

int getScore(string s, int l, int r,char curr)
{
    int score = 0;
    for(int i=l; i<r; i++)
        if(s[i]!=curr)
            score++;
        
    return score;
}
 
int dnc(string s, int left, int right, char curr)
{
    if(left == right) return 0;
    if(right == left+1) return s[left]==curr ? 0 : 1;
    int mid = (left+right)/2; 
 
    return min(getScore(s,left,mid,curr) + dnc(s,mid,right,curr+1),getScore(s,mid,right,curr) + dnc(s,left,mid,curr+1));
}

Solution Link: https://codeforces.com/contest/1385/submission/144376401 (TLE) https://codeforces.com/contest/1385/submission/144376593 (AC)

I see that you're passing the string by value. Every time the function is being called, the string is being duplicated. Compare it to the example that's using char array, the array is declared once and being used without copying. Also online judges won't give you TLE for things like using string vs. char arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM