小优化:减少内存分配次数

main
lensfrex 3 years ago
parent 240fc8f634
commit 3ac0fd4479
Signed by: lensfrex
GPG Key ID: 0F69A0A2FBEE98A0
  1. 16
      work20220407/string/String.cpp

@ -25,7 +25,7 @@ String::String() : String(128) {}
String::String(const char *source) : String(source, (int) strlen(source)) {}
/**
*
*
*/
String::String(const char *source, int length) : String(length + 1) {
strncpy(data, source, length);
@ -152,8 +152,6 @@ void String::addString(const char *source, int sourceLength) {
this->data = new char[allocSize]();
length = sourceLength;
} else {
length = (int) strlen(data);
}
// 如果拼接后字符长度超过已分配的内存大小,则重新分配data内存大小
@ -162,17 +160,17 @@ void String::addString(const char *source, int sourceLength) {
char *old = new char[length + 1]();
strcpy(old, data);
// 重新分配内存,防止拼接后溢出
// 分配两倍内存空间来减少重新分配次数
delete[] data;
allocSize = length + sourceLength + 1;
allocSize = (length + sourceLength)*2 + 1;
this->data = new char[allocSize]();
strcpy(data, old);
}
strcat(data, source);
length = allocSize - 1;
length += sourceLength;
}
/**
@ -217,14 +215,16 @@ char &String::operator[](int i) {
String String::operator+(const char *source) {
int sourceLength = (int) strlen(source);
String target(this->data, this->length + sourceLength + 1);
String target = String((this->length + sourceLength)*2 + 1);
target = this->data;
target += source;
return target;
}
String String::operator+(const String &source) {
String target(this->data, this->length + source.length);
String target = String((this->length + source.length)*2 + 1);
target = this->data;
target += source;
return target;

Loading…
Cancel
Save