devxlogo

Prefer Initialization to Assignment of Objects

In general, assignment requires the creation and destruction of a temporary object, whereas initialization does not. This is true for not just for strings, but for every object type, so whenever you have the choice–prefer initialization to assignment. Consider this code snippet:

     string s1 = "Hello ",  s2 = "World", both;    both = s1+s2;   // assignment rather than initialization; inefficient 

The compiler transforms the expression both = s1+s2; into:

     string temp (s1 + s2);  // store result in a temporary    both = temp;   // assign     temp.Date::~Date();  // destroy temp

This snippet could have been written in a much more efficient way:

     string s1 = "Hello ",  s2 = "World";    string both = s1+s2;  // initialization is more efficient than assignment

This time, the compiler transforms the expression both = s1+s2; into:

     string both (s1 + s2); 

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.