3 ms·
The lambda approach is slower because a function call always has some overhead. In lower-level C-like languages the overhead is usually lighter than in interpre
by thegeomaster 12y ago
The lambda approach is slower because a function call always has some overhead. In lower-level C-like languages the overhead is usually lighter than in interpreted languages such as Python. In this case, reduce will have to call the lambda everytime, which is a few more instructions for the processor and some checking by the interpreter. Then the lambda will compute the sum, and then return to the caller. It's not a lot of time, but it's certainly faster than knowing what you need to do at the call site.
As srean pointed out, however, it's not all black and white like I described. He raises some good points like what the Python interpreter does when it needs to look up the type of the variable, etc etc.
I come across those kinds of "it's obvious" things all the time, too, especially in the world of more functional and powerful languages. When people write Ruby or Lisp (I'm learning them ATM) some solutions are simply obvious to them, when I would've done the complete opposite. I got used to this and simply accepted that these will become obvious to me one day, when I grok the concepts. And when I really don't understand something that is "obvious", I ask, and people are very happy to explain it to me. I've never once encountered a condescending reaction. So no need to get upset because of it. We're all used to doing different things and different things are obvious to us. Doesn't mean that anyone is arrogant or something, it's simply that people usually look at the world through their own eyes :)