Вопрос

I was experimenting with C++ to observe the effects of variables' scope-bounded-declarations and usage in loops on the running time of the program, as follows:

for(int i=0; i<10000000 ; ++i){
    string s = "HELLO THERE!";
}

and

string s;
for(int i=0; i<10000000 ; ++i){
    s = "HELLO THERE!";
}

The first program run in ~1 second while the second one run in ~250 milliseconds, as expected. Trying built in types wouldn't cause a significant difference, so I stick with strings in both languages.

I was discussing this with a friend of mine and he said this wouldn't happen in C#. We tried and observed ourselves that this did not happen in C# as it turned out, scope-bounded declarations of strings won't affect running time of the program.

Why is this difference? Is that a bad optimization in C++ strings (I strongly doubt that tho) or something else?

Это было полезно?

Решение

Strings in C# are immutable, so the assignment can just copy over a reference. In C++, however, strings are mutable, so the entire contents of the string need to be copied over.

If you want to verify this hypothesis, try with a (significantly) longer string constant. Runtime in C++ should go up, but runtime in C# should remain the same.

Другие советы

Strings in C# are immutable. C# uses references and the memory it's not copied!

in C# "HELLO THERE!" will be automatically assigned to a piece of memory and won't be copied each time for example:

string a = "HELLO"; string b = a;

they are pointing to the same piece of memory, but in C++ no! the string will be the same but not in the same place, if you want to obtain the same reult you should use pointers (or smart pointers)

string *a = new string("hello"); string *b = a;

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top