2

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?

1
  • 9
    I'm fairly sure you did this test without optimizations enabled in C++. Most C++ compilers will get rid of that entire chunk of code because it has no observable side effects. Commented Apr 26, 2014 at 19:34

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Right, the equivalent in C++ would be to use const char* s;
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.