Book_Op_4 - 8BitsCoding/RobotMentor GitHub Wiki
string의 ASCII 문자만 남겨보자
// CASE 1
std::string remove_ctrl(std::string s) {
std::string result;
for(int i = 0; i < s.length(); ++i) {
if(s[i] > = 0x20)
result = result + s[i];
}
return result;
}
좀 더 빠르게 ...
+ -> +=
// CASE 2
std::string remove_ctrl(std::string s) {
std::string result;
for(int i = 0; i < s.length(); ++i) {
if(s[i] > = 0x20)
// + -> +=
result += s[i];
}
return result;
}
result + s[i];
의 결과를 임시 저장하는 메모리의 복사 및 삭제 연산을 줄여준다.
string의 저장공간 예약( reserve() )
// CASE 3
std::string remove_ctrl(std::string s) {
std::string result;
// reserve()
result.reserve(s.length());
for(int i = 0; i < s.length(); ++i) {
if(s[i] > = 0x20)
// + -> +=
result += s[i];
}
return result;
}
매개변수의 복사 제거 (std::string const& s)
// CASE 4
// const& s
std::string remove_ctrl(std::string const& s) {
std::string result;
// reserve()
result.reserve(s.length());
for(int i = 0; i < s.length(); ++i) {
if(s[i] > = 0x20)
// + -> +=
result += s[i];
}
return result;
}
이렇게 하면 성능 개선이 될 것 같지만 성능이 악화된다...
s는 참조자이기에 다시한 번 포인터 참조를 해야하는 역참조 현상때문이다.
역참조를 직접참조로 변경
// CASE 5
// const& s
std::string remove_ctrl(std::string const& s) {
std::string result;
// reserve()
result.reserve(s.length());
for(auto it = s.begin(), end = s.end(); it != end; ++it) {
if(*it >= 0x20)
result += *it;
}
return result;
}
메모리를 직접참조함으로서 성능 개선
리턴형도 복사를 막아보자
// CASE 6
// const& s
std::string remove_ctrl(
std::string& result
std::string const& s)
{
result.clear();
result.reserve(s.length());
for(auto it = s.begin(), end = s.end(); it != end; ++it) {
if(*it >= 0x20)
result += *it;
}
return result;
}
최적의 방법은 c스타일로 코딩이다...
void remove_ctrl+cstrings(char* destp, char const* srcp, size_t size) {
for(size_t i = 0; i < size; ++i) {
if(srcp[i] >= 0x20)
*destp++ = srcp[i];
}
*destp = 0;
}