Is a function defined within a recursive function bad?

0

Hello. I had in javascript a code something like this:

function loop (i) {
    function callback () {
        // fazia alguma coisa
        if (i < 10) loop(++i);
    }
    setTimeout(callback, 1000);
}

Basically a function that is called by setTimeout and that is defined inside a function that it will call again. Is there a performance problem in this? In python or other language is this also bad?

    
asked by anonymous 29.10.2017 / 12:57

1 answer

0

There is no problem at all and no performance cost. Even this practice is used in many frameworks, such as jQuery.

However, as with anything else related to programming, depending on the case, this may or may not be the best approach. In many cases where setTimeout is used (but not at all), it may be worthwhile to use asynchronous functions . Again, this is a tool that the developer has to use, and like any other tool, has occasions where it is a good alternative to use and occasions where it is not. For example, a hammer can be an excellent tool for nailing nails, but it will have a very bad result if you need to cut a piece of wood.

The use of functions within functions (often anonymous) is a feature widely used in various programming languages on the < strong> lambda .

Python is a language that implements lambdas . Java 8 and above also (although it was possible and common to simulate this with anonymous classes since Java 1.1). C # also implements this concept. JavaScript implements since birth. Pascal has that too. This concept is widespread, although it has been neglected for a long time in many programming languages, including some that were already adopted from the beginning, and only began to be valued from the 2000s.

Some languages have adopted this very late, such as C ++, which has just implemented lambdas from the 2011 version , although function pointers were being used to do this from the early versions of C (however, not allowing you to put one function inside the other and with horrible and very discouraging syntax).

As for the difference in performance, this obviously depends on language, but in almost all of them this difference, when it exists, is so small that it is not even measurable.

    
29.10.2017 / 15:00