Hi codeforces , I was arguing with my friend about which is the best type of functions , so we had to try every type of functions in c++ .
I tried all three types of functions on some recursion problems and I got the following result :
Time complexity :
- normal function : it was the fastest .
- lambda function : it was slower than the normal function by 20 ms .
- std function : it was slower than the previous two by 200 ms .
Memory complexity :
- std function : was the best .
- normal function : was worse than std function by 30000 kb (maybe that's because of changing the arrays' identification to a global scope with const length)
- lambda : was exactly the same as the normal function (without using global scope) .
this result was satisfying but when I tried on other problems a contradictory result appeared :
Time complexity :
- normal function : it was the fastest .
- std function : it was slower than the normal function by 100 ms .
- lambda function : it was slower than std by 30 ms .
Memory complexity :
- std function : was the best .
- lambda : was worse than std function by 100 kb (nothing) .
- normal function : was worse than std function by 6000 kb (maybe that's because of changing the arrays' identification to a global scope with const length) .
so I was wondering what is the best type of functions for time complexity and memory complexity (depending on assembly and how many additional assembly lines for every type) cause even reading the documentation wasn't useful .
thanks in advance .
the unexpected result submission links :









Generally aim to use functors, lambdas, and normal functions. Those three can be resolved and inlined at compile time. std::function is a polymorphic wrapper that is resolved at runtime, which is much slower.
In general it would but the compiler can optimise if it sees what's actually going on.
The time differences you're seeing are basically random noise and yes, the memory difference is likely due to using globals. You're using lambdas in the "std" case too, just wrapping them in more modern objects. There can be slight overhead involved there from not using statically defined (normal) functions but compared to everything that goes on during a function call, it shouldn't matter for you.
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." — Donald Knuth