使用Symfony进行Ajax响应时间

Ajax is taking 1sec to load in dev and 500ms in prod with Symfony2 with a really simple call :

Javascript :

$.ajax({
            url: "{{ path('my_path') }}",
            type: 'GET',
            data: {x: x},
            dataType: 'json',
        }).done(function(res) {

        });

Controller :

/**
 * @Route("/my_path", name="my_path", condition="request.isXmlHttpRequest()")
 * @Method("GET")
 */
public function myPathAction(Request $request)
{
    return new JsonResponse('');
}

If I change the url in my ajax call by

url: "test.php"

With test.php :

return json_encode('');

In both case we are doing the same thing but accessing to a controller take 500ms in prod and accessing to "test.php" takes 20ms.

Why does Symfony takes that much time to access to the route and how can I make it faster ?

Please not that the Symfony action is also checking if it's a GET request and a XmlHttpRequest, etc. etc. So even if you can make it faster, you'll never get it as fast as 'vanilla' PHP. A framework like Symfony is a great toolbox, but will add some overhead in return.

Performance is really important, but very complex. There are 1000 things you can do to get a better performance. Just some thoughts:

  • First of all: read the documentation about Performance in the Symfony Book. Opcache/APC really helps.
  • Use the Web Debug Toolbar to see what's happening during a request. Is it the router part? Security? Or the templating?
  • Use your browser's console (F12 for the Chrome Console) to see what's the difference between test.php and /my_path. Check the request/response headers to see what's the difference.
  • I just switched to PHP 7 and the performance increase is impressive.

Somebody downvoted your question and I can imagine why. When I started using Symfony, performance was a big concern for me as well. So is it for many other developers, so there are many other articles, questions, etc. you can find. Please read the documentation, search on Google/StackOverflow, etc.

  • 500ms (with "{{ path('my_path') }}") because the process work with routing symfony2 system
  • 20ms (with "test.php") because you target directly the file for working with AJAX call