Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suggested speed improvement when defining string with value immediately, instead of delaying

I'm currently reading in "The C++ Programming Language: Special Edition" by Bjarne Stroustrup and on page 133 it states the following:

For user-defined types, postponing the definition of a variable until a suitable initializer is available can also lead to better performance. For example:

string s;  /* .... */ s = "The best is the enemy of the good.";

can easily be much slower than

string s = "Voltaire";

I know it states can easily, which means it won't necessarily be so, however let's just say it does occur.

Why would this make a potential performance increase?

Is it only so with user-defined types (or even STL types) or is this also the case with int, float, etc?

like image 911
Tony The Lion Avatar asked Jan 18 '12 17:01

Tony The Lion


People also ask

How can I improve my Powerapps performance?

For example, you can move some functions to the OnVisible property instead. This way you can let the app start quickly, and other steps can continue while the app opens. We recommend using App. StartScreen property since it simplifies app launch and boosts the app's performance.

How do you shorten a string in C++?

As Chris Olden mentioned above, using string::substr is a way to truncate a string. However, if you need another way to do that you could simply use string::resize and then add the ellipsis if the string has been truncated. You may wonder what does string::resize ?


1 Answers

I'd say this is mainly about types with non-trivial default constructors, at least as far as performance is concerned.

The difference between the two approaches is that:

  • In the first version, an empty string is first constructed (using the default constructor); then the assignment operator is used to effectively throw away the work done by the default constructor, and to assign the new value to the string.
  • In the second version, the required value is set right away, at the point of construction.

Of course, it is really hard to tell a priori how big a performance difference this would make.

like image 136
NPE Avatar answered Oct 13 '22 00:10

NPE