Search code examples
phpgoogle-cloud-platformgoogle-translate

Google translate API POST 11second delay?


EDIT: 11.5 seconds for 28 messages

Single requests work fine. This code below takes 11 seconds, measured using postman setting route in API to access.

Am I doing something wrong? I feel as though it shouldn't take 11 seconds even without cache.

$xs = ChatMessage::where('chat_room_id','=',$roomId)
->with('user')
->orderBy('created_at','DESC')
->get();



    foreach($xs as $r){
            
        $translate = new TranslateClient([
            'key' => 'xxxxxxxxxxxxxxxxxxxxxxx'
        ]);
        
        $result = $translate->translate($r->message_english, [
            'target' =>'es',
            'source' => 'en',
        ]);
        
        $r->message = $result['text'];
    }

return $xs;

Solution

  • I think you can easily speed the process by just moving the client out of the for each loop. You are creating a client each time you iterate. That's not optimal. You should be able to reuse the client per translate call. That should speed your translation process. You can find samples of this usage in the official github client project

    Here is a pseudo code sample:

    client = new TranslateClient()
    
    foreach(message in messages)
       result = client.translate(message)
       print(result)
    

    Also, how long is your translated text? You should pass the whole text to be translated into a single call (as long as the supported library allows) So you also reduce the calls done to the API.

    If you still have issues you can go by using multiple request in parallel as mentioned in the comments.

    Some useful links about this: