C++ 两种代码写法的效率比较
迷茫
迷茫 2017-04-17 11:16:42
0
4
541

源代码:

// 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);
}

这样会不会提高代码效率? 为什么?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
大家讲道理

The first way of writing opens a char and a MyString * 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 of char 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 and operator +=. You can repeat it 10,000 times to 10,000 times and measure the time.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template