Cameron
Cameron

Reputation: 15

Performance benefit of adding function to $scope?

Is there a major performance benefit to adding a function to $scope that doesn't need to be on $scope?

example:

function myCtrl($scope){
    $scope.myFunc = function(){
        // my function on scope
        var four = myHelperFunc(2);
        return four;
    }

    function myHelperFunc(number){
        // my helper function
        return number * 2;
    }
}

versus:

function myCtrl($scope){
    $scope.myFunc = function(){
        // my function on scope
        var four = $scope.myHelperFunc(2);
        return four;
    }

    $scope.myHelperFunc = function(number){
        // my helper function on scope
        // is this better than the previous example?
        return number * 2;
    }
}

Upvotes: 0

Views: 48

Answers (2)

Jeremy Likness
Jeremy Likness

Reputation: 7531

There is not a performance benefit to the latter. In the end, a function is still called. The difference is whether you want your helper function to be able to be called from the UI. On the $scope you can code a call to it, inside the controller you control access and only call it from your functions. It's more an API visibility concern than a performance one.

Upvotes: 0

pid
pid

Reputation: 11607

The first is better, it will use lexical scoping. The second will use object state memory on the heap. As the number of objects grows, you'll consume more memory just to keep the reference $scope.myHelperFunc.

All in all, I'd recommend to not worry about this, it's better to write clean code that expresses what you are doing. Performance difference is really minimal in this example and it depends on the actual vendor's JS engine implementation on the client side, which you can't really control. Unless... it's server side code.

Upvotes: 2

Related Questions