Re: String performance
Gianni Mariani wrote:
:: Marcin Kalicinski wrote:
:::: You didn't answer Bo's question. First you were testing vector
:::: against string, now you've thrown in a string array.
:::
::: Ok, you're right. I should also have used C++ array instead of
::: std::vector with reserve. So there we go:
:::
::: std::string v[10000000];
::: int main()
::: {
::: clock_t t1 = clock();
::: for (int i = 0; i < 10000000; ++i)
::: v[i] = "foo";
::: clock_t t2 = clock();
::: cout << double(t2 - t1) / CLOCKS_PER_SEC;
::: }
:::
::: Result: 0.42s
:::
::: Faster than vector+reserve, but still 3x slower than C# 0.14s...
:::
::: At that point I must say that I've started using .NET only quite
::: recently, but I've been programming C++ for some 10 years now. So
::: initially I approached this C# thing with a lot of prejudicament
::: on how slow and bloated it's gonna be compared to C++. But it
::: turned out the opposite. It's blazing fast. Granted you can
::: eventually write a program in C++ that is faster than C# version.
::: But you must try really hard and go very low. Forget any nice
::: abstractions like std::string. To be faster you have to use
::: strlen, strcmp, allocate your strings from pools, manually manage
::: pointers, basically go through hell. And even then your string
::: code may be just slightly faster.
::
:: Correct me if I am wrong but your C# example not allocating any new
:: strings while the C++ version does !
::
:: The languages are different and you're not measuring apples to
:: apples. In many cases, it would be that you would do things less
:: efficiently is C++ and in many cases not. Performance really only
:: matters when it can make a difference and C++ has many tools
:: available to you when you need it. I don't know about C# enough
:: to comment.
::
Right. If all I really wanted was a vector of 10 million identical
strings, I would do it like this:
// #1c: C++
int main()
{
std::clock_t t1 = std::clock();
std::vector<std::string> v(10000000, "foo");
std::clock_t t2 = std::clock();
std::cout << double(t2 - t1) / CLOCKS_PER_SEC;
}
And it runs even faster.
Bo Persson