[英]Why is my c++ sorting function so much slower than my c# sorting function?
我是c++的新手,但我确实有其他面向 object 的编程语言的经验。
我试图按字母顺序对我拥有的文件中的行进行排序,该文件大约有 5300 行。 我最初在c++中编写程序用于练习,但很好奇它对我的主要语言c#的表现如何。
令我惊讶的是,我的c++ function 需要 18-20 秒执行的相同排序算法在c#中不到 3 秒就完成了。
鉴于我是c++的新手(一般来说不是一个非常有经验的程序员),我确信这一定是我写东西的方式的错误。
综上所述,我知道可以使用更快的排序方法。 但是,这两个程序都使用相同的算法,所以我不明白性能差距很大的原因。
我会注意到我已经尝试将数据转换为数组而不是vector ,但是对数组进行排序只持续快了大约 3 秒(总共大约 15 秒而不是 18 秒)。
我究竟做错了什么? 任何/所有帮助表示赞赏!
下面是c++:
void select_sort_alphabetical(std::vector<std::string> _vector)
{
std::cout << "<< SORTING... >>" << "\n\n";
int char_index, i, j, size = _vector.size(), loop_iterations = 0;
char char1, char2;
std::string temp;
// Iterate through all lines
for (i = 0; i < (size - 1); i++)
{
for (j = (1 + i); j < size; j++)
{
char_index = 0;
char1 = _vector[i][char_index]; // Getting first character of each line
char2 = _vector[j][char_index];
// While the letters to be compared are the same, move onto the next character
while (char1 == char2)
{
char_index++;
char1 = _vector[i][char_index]; // Setting chars to the next characters in each line
char2 = _vector[j][char_index];
}
// Once the characters are different - if line x.ascii_code greater than line x+1.ascii_code...
if (_vector[i][char_index] > _vector[j][char_index]) // comparing characters
{
// Swapping places
temp = _vector[i];
_vector[i] = _vector[j];
_vector[j] = temp;
}
loop_iterations++;
}
}
//print_lines_from_vect(_vector);
// Clearing contents of vector and freeing up memory (trying to, anyway)
_vector.clear();
_vector.shrink_to_fit();
std::cout << "\nIterations: " << loop_iterations << "\n";
}
这是 c#:
public static string[] select_sort_alphabetical(string[] lines, ref int loop_iterations)
{
Console.WriteLine("<< SORTING... >>");
// Iterate through all lines
for (int i = 0; i < (lines.Length - 2); i++)
{
for (int j = (1 + i); j < (lines.Length); j++)
{
int char_index = 0;
char char1 = lines[i][char_index]; // Getting first character of each line
char char2 = lines[j][char_index];
// While the letters to be compared are the same, move onto the next character
while (char1 == char2)
{
char_index++;
char1 = lines[i][char_index];
char2 = lines[j][char_index];
}
// Once the characters are different - if line x.ascii_code greater than line x+1.ascii_code...
if (lines[i][char_index] > lines[j][char_index]) // comparing characters
{
// Swapping places
string temp = lines[i];
lines[i] = lines[j];
lines[j] = temp;
}
loop_iterations++;
}
}
return lines;
}
如果不考虑语言之间的其他差异,您的算法会变慢的原因之一是换行:
// Swapping places
string temp = lines[i];
lines[i] = lines[j];
lines[j] = temp;
string temp = original
表示temp
和original
指向同一个字符串。 修改每个将反映在另一个。string temp = original
表示temp
是一个新字符串。 修改一个不会修改另一个。C++提供move class成员,允许新对象“窃取”原object的资源。
std:.swap
,为了交换对象,做一些像
string temp = steal(lines[i]);
lines[i] = steal(lines[j]);
lines[j] = steal(temp);
这是对真实机制的简化。
顺便说一句,如果你使用 swap,你会看到更快的调试,因为行交换在你的算法中是一个很大的成本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.