Is ans+=s[i] faster than ans = ans+s[i] ?
I was able to submit my solution by just replacing ans = ans+s[i] with ans+=s[i].🐰
With ans = ans+s[i] I got TLE and the same code with ans+=s[i] was 70% faster solution.👀
Amazing isn't it??
But why let's find out.
-> ans+=s[i] means
0. Find the place identified by ans in the memory
1. Add s[i] to it
-> But ans = ans + s[i] means:
0. Evaluate ans+s[i]
1. Find the place identified by ans
2. Copy ans into an accumulator
3. Add s[i] to the accumulator
4. Store the result in ans
5. Find the place identified by ans
6. Copy the accumulator to it
In this one, the memory block where ans is kept will be searched 2 times and searching has side effects.😕
This is the reason ans+=s[i] is faster than ans = ans+s[i].🙂
Like it, if you found it informative.
and follow Nikhil Bhatia for more
#competitiveprogramming #datastructures #programming #leetcode #codechef #amazon #opensource #linkedin
I was able to submit my solution by just replacing ans = ans+s[i] with ans+=s[i].🐰
With ans = ans+s[i] I got TLE and the same code with ans+=s[i] was 70% faster solution.👀
Amazing isn't it??
But why let's find out.
-> ans+=s[i] means
0. Find the place identified by ans in the memory
1. Add s[i] to it
-> But ans = ans + s[i] means:
0. Evaluate ans+s[i]
1. Find the place identified by ans
2. Copy ans into an accumulator
3. Add s[i] to the accumulator
4. Store the result in ans
5. Find the place identified by ans
6. Copy the accumulator to it
In this one, the memory block where ans is kept will be searched 2 times and searching has side effects.😕
This is the reason ans+=s[i] is faster than ans = ans+s[i].🙂
Like it, if you found it informative.
and follow Nikhil Bhatia for more
#competitiveprogramming #datastructures #programming #leetcode #codechef #amazon #opensource #linkedin