过度使用 realloc
Overuse of realloc
将数据读入字符串时,是根据需要使用尽可能多的 realloc
以获得正确的内存量更好,还是使用更少的 realloc
' 更好? s 但最终可能会出现未使用的内存?
例如,这样更好吗:
char c;
int count = 1;
char* s = malloc(sizeof(char));
while((c = fgetc(file)) != EOF) {
char* snew = (char *)realloc(s, count*sizeof(char));
if(!snew) {
exit(1);
}
s = snew;
s[count-1] = c;
count++;
}
或者这样更好:
char c;
int count = 0;
int size = 1;
char* s = malloc(sizeof(char));
while((c = fgetc(file)) != EOF) {
s[count] = c;
count++;
if(count >= size) {
size*=2;
char* snew = (char *)realloc(s, size*sizeof(char));
if(!snew) {
exit(1);
}
s = snew;
}
}
如今内存充足,因此拥有准确的内存量并不像减少 运行 时间那么重要。
第二种方案,即在需要更多内存时将分配的内存加倍,通常被认为是更好的选择。
后者 绝对 如果你有不受约束的行长度,因为构建长度为 n
的字符串所花费的时间将是 O(n)
而前者是 O(n²)
由于不必要的复制。如果你想减少过度分配,你可以权衡一个更高的常数因子——例如,总是增加缓冲区 20% and 1 个字符。
P.S。 - 否则在 char
未签名的平台上没有足够的内存...
将数据读入字符串时,是根据需要使用尽可能多的 realloc
以获得正确的内存量更好,还是使用更少的 realloc
' 更好? s 但最终可能会出现未使用的内存?
例如,这样更好吗:
char c;
int count = 1;
char* s = malloc(sizeof(char));
while((c = fgetc(file)) != EOF) {
char* snew = (char *)realloc(s, count*sizeof(char));
if(!snew) {
exit(1);
}
s = snew;
s[count-1] = c;
count++;
}
或者这样更好:
char c;
int count = 0;
int size = 1;
char* s = malloc(sizeof(char));
while((c = fgetc(file)) != EOF) {
s[count] = c;
count++;
if(count >= size) {
size*=2;
char* snew = (char *)realloc(s, size*sizeof(char));
if(!snew) {
exit(1);
}
s = snew;
}
}
如今内存充足,因此拥有准确的内存量并不像减少 运行 时间那么重要。
第二种方案,即在需要更多内存时将分配的内存加倍,通常被认为是更好的选择。
后者 绝对 如果你有不受约束的行长度,因为构建长度为 n
的字符串所花费的时间将是 O(n)
而前者是 O(n²)
由于不必要的复制。如果你想减少过度分配,你可以权衡一个更高的常数因子——例如,总是增加缓冲区 20% and 1 个字符。
P.S。 char
未签名的平台上没有足够的内存...