I have questions about design and what can C++ compilers do in those situations.
Q. What kind of approaches you use on situations where you want to separate common parts of multiple functions in order to gain perfomace boost, whilst keep client away from those details?
In detail:
- Let me use pseudocode of mix of C++ and Python.
- Assume that client is me. I want to have reusable functions as interface.
- Suppose I've written some statements.
client():
commonExpression //This is used by A and B statements. Evaluated once
statementOfA
statementOfA
...
statementOfB
statementOfB
...
- Then I want to refactor this in order to gain readability and reusability in the future. In this case I implement those functions with individiual commonExpression in each of them. Hence, in client context, commonExpression is evaluated twise. This is what I want to give a client - a clean interface without implementation details
client():
doA() // uses one instance of commonExpression
doB() // uses one instance of commonExpression
- If I want to use only one function, no problems
otherClient():
doA()
- But if I want to gain potential perfomance boost, I'd create something like this
client():
//commonExpression is evaluated once instead of 2 times
commonExpression
doA(commonExpression.result)
doB(commonExpression.result)
- This seems very verbose for me, I'd rather use doA() whith commonExpression in it. Q. Isn't it better to give a client a clean function without some kind of injection, not related to OOP?
otherClient():
commonExpression
doA(commonExpression.result)
- I can create wrappers, leading to overcomlicated interface:
doAWrapper():
commonExpression
doA(commonExpression.result)
doBWrapper():
commonExpression
doB(commonExpression.result)
doAandBWrapper():
commonExpression
doA(commonExpression.result)
doB(commonExpression.result)
C++ compiler optimizations and inlined functions.
- Q. Can compiler do this optimization at assembly level?:
client():
doA() // uses one instance of commonExpression
doB() // uses one instance of commonExpression
Optimized by compiler. Compiler sees common parts:
client():
commonExpression
statementOfA
...
statementOfB
...
- Q. Are compilers smart enough to clamp 2 functions as one if I mark them as inline?:
client():
doA() // uses one instance of commonstatemet
doB() // uses one instance of commonstatemet
As:
client():
commonExpression
statementOfA
...
statementOfB
...
Or they will unroll to:
client():
commonExpression1
statementOfA
...
commonExpression2
statementOfB
...
Remark: When I was about to end previous lines, I remembered about singletones and flyweight patterns) I think this topic dive very deep. But I dont want to overcomlicate my code(hello KISS). There must be a simple way) And I'm asking you, expirienced ones, for advice
- Q. What kind of approaches you use on those situations?
Aucun commentaire:
Enregistrer un commentaire