Is a function defined within a recursive function bad?

Asked

Viewed 55 times

0

Hello. I had in javascript a code more or less 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 it is set within a function that it will call again. Is there a performance problem in that? In python or other language this is also bad?

  • 1

    What would be the object of this function? An internal function that uses the scope of its parent function we call closure. To define whether this should be done or not, it is necessary to describe what the purpose of the function is; it depends on the "something" within it.

1 answer

0

There is no problem in this and no cost of performance. Even this practice is used in several 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 the setTimeout is used (but not all), it may be interesting to use asynchronous functions. Again, this is a tool that the developer has to use, and like any other tool, it 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 affixing nails, but it will have a bad result if what you need is to cut a piece of wood.

The use of functions within functions (often anonymous) is a feature widely used in several programming languages under the name of lambda.

Python is a language that implements Both. Java 8 and higher also (although it was possible and common to simulate this with anonymous classes since Java 1.1). C# also implements this concept. Javascript has been implementing since its inception. Pascal also relies on this. This concept is quite widespread, although it is something that has been neglected for a long time in several programming languages, including some that were already adopted from the beginning, and only started to be valued from the 2000s.

Some languages adopted this very late, such as C++, which only implemented Lambdas from the 2011 version, although pointers to functions were being used to do this from the early versions of C (however, without allowing one function to be placed inside the other and with a horrific and very discouraging syntax).

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.