源代码:
// Blahblah~
{
////////////////////////////////
// 写法一 BEGIN
//char realc = (char) c;
//outString->append( &realc, 1 );
// 写法一 END
////////////////////////////////
////////////////////////////////
// 为什么写法二是"more efficient function call?"
*outString += (char) c; // somewhat more efficient function call.
////////////////////////////////
++i;
}
// Blahblah~
而重载的+=
运算符的操作是这样的
这个函数写在类定义里~应该会转化成内联(?)
// += operator. Maps to append
MyString& operator += (char single)
{
return append(&single, 1);
}
这样会不会提高代码效率? 为什么?
The first way of writing opens a
char
and aMyString *
in the stack memory. The second way of writing is the same. Even if the compiler optimization can recognize and use the internal Connection, but due to forced type conversion, the stack memory ofchar
still cannot be saved.I don’t think there will be any improvement in efficiency. The "efficiency improvement" of this writing method is to improve the self-explanatory power of the code and reduce the reading burden on humans. After all, a programmer's time reading code is valuable, especially during the maintenance phase of software.
In addition to execution efficiency, code efficiency should also include maintenance efficiency.
For example,
+=
in the second paragraph of code. People who have even a little bit of programming experience will understand it at a glance and will not repeatedly try to figure out what your line of code means when reading the code. , which saves his time and also saves you the time of explaining things clearly to him over and over again.When there is not much difference in execution efficiency, choosing code that conforms to human reading habits is also a manifestation of efficiency.
I don’t think the second method has any improvement in maintenance efficiency. For the string type, I don’t know whether append is more clear or writing += is more clear. I think it is append.
What is actually being compared is the efficiency of the two functions
append
andoperator +=
. You can repeat it 10,000 times to 10,000 times and measure the time.