Masoud
Masoud

Reputation: 1405

Different benchmarks for string manipulation in C# and C++

I have two very simple code in C++ and C# in c#

for (int counter = 0; counter < 100000; counter ++)
{
    String a = "";
    a = "xyz";
    a = a + 'd';
    a = a + 'c';
    a = a + 'h';
}

in c++

for (int counter = 0; counter < 100000; counter ++)
{
    string a = "";
    a.append("xyz");
    a = a + 'd';
    a = a + 'c';
    a = a + 'h';
}

the strange thing is the c# code took 1/20 time for execution than the c++ code. could you please help me to find why this happened? and how can I change my c++ code to become faster.

Upvotes: 2

Views: 532

Answers (2)

Krešimir Lukin
Krešimir Lukin

Reputation: 399

For large string manipulation use StringBuilder

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182753

It's probably a quirk of the implementations. For example, one optimizer might have figured out that the result of the operations isn't used. Or one might happen to allocate a string large enough to add three extra characters without reallocating while the other didn't. Or it could be a million other things.

Benchmarking with "toy" code really isn't helpful. I wouldn't assume the results apply to any realistic situation.

There are so many obvious optimizations to this code, for example:

string a;
for (int counter = 0; counter < 100000; counter ++)
{
    a = "xyz";
    a.append(1, 'd');
    a.append(1, 'c');
    a.append(1, 'h');
}

That may make a huge difference by reusing the buffer and avoiding extra allocate/copy/free cycles.

Upvotes: 6

Related Questions