Coding Practices which enable the compiler/optimizer to make a faster program

后端 未结 30 1932
一个人的身影
一个人的身影 2020-12-02 03:24

Many years ago, C compilers were not particularly smart. As a workaround K&R invented the register keyword, to hint to the compiler, that maybe it woul

30条回答
  •  长情又很酷
    2020-12-02 03:59

    Don't do the same work over and over again!

    A common antipattern that I see goes along these lines:

    void Function()
    {
       MySingleton::GetInstance()->GetAggregatedObject()->DoSomething();
       MySingleton::GetInstance()->GetAggregatedObject()->DoSomethingElse();
       MySingleton::GetInstance()->GetAggregatedObject()->DoSomethingCool();
       MySingleton::GetInstance()->GetAggregatedObject()->DoSomethingReallyNeat();
       MySingleton::GetInstance()->GetAggregatedObject()->DoSomethingYetAgain();
    }
    

    The compiler actually has to call all of those functions all of the time. Assuming you, the programmer, knows that the aggregated object isn't changing over the course of these calls, for the love of all that is holy...

    void Function()
    {
       MySingleton* s = MySingleton::GetInstance();
       AggregatedObject* ao = s->GetAggregatedObject();
       ao->DoSomething();
       ao->DoSomethingElse();
       ao->DoSomethingCool();
       ao->DoSomethingReallyNeat();
       ao->DoSomethingYetAgain();
    }
    

    In the case of the singleton getter the calls may not be too costly, but it is certainly a cost (typically, "check to see if the object has been created, if it hasn't, create it, then return it). The more complicated this chain of getters becomes, the more wasted time we'll have.

提交回复
热议问题