One of my programs is exceeding the time limit when I am using fans = fans + s[i]
, while when I am using fans += s[i]
it is being accepted... Why does this happen? To Explain more , fans is a string and s is also a string so while iterating over string s i want only some characters of s so i am creating a new string fans.Now there are two ways in which i can add character to my new string fans. The Problem is mentioned below
fans = fans + s[i]; // gives Time limit exceeded fans += s[i]; // runs successfully
String s1 = "Hello". Here, hello string will be stored at a location and and s1 will keep a reference to it. String s2=new String("Hello") will create a new object, will refer to that one and will be stored at a different location.
String s= new String (“abc”) is guaranteed to be a new String object. String objects created using 'new' operator are stored in the heap.
In other words doing String s = new String("ABC") creates a new instance of String , while String s = "ABC" reuse, if available, an instance of the String Constant Pool.
Suppose s1 and s2 are two String objects. If: s1 == s2 : The method returns 0. s1 > s2 : The method returns a positive value. s1 < s2 : The method returns a negative value.
For built-in types a += b
is exactly the same as a = a + b
(except that a
is evaluated only once), but for classes, those operators are overloaded and call different functions.
In your example fans = fans + s[i]
creates a temporary string, and assigns (moves) it to fans
, but fans += s[i]
does not create that temporary, hence it may be faster.
std::string
has members operator +
and operator +=
. The former is usually implemented with the latter by way of an intermediate temporary. Effectively looking something like this (check your implementation source if you want to know exactly what yours does):
/// note reference return type std::string& operator +=(char c) { this->append(c); return *this; } // note value return type std::string operator +(char c) const { std::string tmp = *this; tmp += c; // or just tmp.append(c) directly return tmp; }
The setup of tmp
is expensive. The overall function can (and usually is) made better with move-assignment semantics to the final destination on the caller-side, but the expense of the temporary is none-the-less still there. Do it a few times and you won't notice the difference. Do it thousands, or millions, etc. of times, and it can mean a world of difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With