Question

I have a really simple resource calling CakePHP. When I run the request using Advanced Rest Client it returns in ~100ms. In angular it takes 2-4 seconds. Below is the code I'm running to "prove" that resource is the bottleneck.

Resource:

var resource = $resource('/index.php/props/:op/:id.json', {}, {
    getPropertyListByCategory: { method:'GET', params:{ op:'getPropertyListByCategory', category:'@category' } },
    setPropertyListByCategory: { method:'POST', params:{ op:'setPropertyListByCategory' } }
});

Method:

function getPropertyListByCategory(params) {
    var x1 = Date.now();
    var deferred = $q.defer();
    resource.getPropertyListByCategory(params, function(resp) {
        var x2 = Date.now();
        console.log(x2-x1);
        deferred.resolve(resp.data);
    });
    return deferred.promise;
}

You can see I timestamp right before the resource call, then compare it to the resolve. Again when I run this request directly against Cake it returns super fast. Cake is not the problem.

Any ideas how I can speed this up a little bit?

Was it helpful?

Solution

$resource is not slow

I wanted to put it inside a comment but it is too long to fit, so..

It might be tempting to think that $resource is the bottleneck here, but I suggest it's because you don't fully understand how asynchronous code works and more than that how angular works.

Your "benchmark" is not valid, it assumes the callback is invoked immediately, and no other code runs in between.

See this question: AngularJS: Why does $http not actually make a http request until you leave the current digest?

$resource uses $http which will not actually send the request until the next $digest() is executed.

Lots of things can make a $digest slow, you should check other parts of your application for it.

You may also create an angular test application with only $resource and see if it is still slow.

If you think about it , when was the last time you heard about an angular.js performance issue which do not involve $digest ?!

Again, What could be slow with $resource?! it's just a simple service.


function getPropertyListByCategory(params) {
    var x1 = Date.now();
    var deferred = $q.defer();

    // the request is queued and will run after a $digest!!
    resource.getPropertyListByCategory(params, function(resp) {

        var x2 = Date.now();
        deferred.resolve(resp.data);
    });

    // x3 is assigned before x2 ..

    var x3 = Date.now();

    return deferred.promise;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top