Search code examples
google-apps-scriptgoogle-contacts-api

Execution time too long Google AppsScript


I created this script to capitalize family names in Google Contacts. Only the script takes too much time. An idea ?

function nomDeFamilleEnMajuscules() {
  Logger.clear();
  var contacts = ContactsApp.getContacts();
  for (var i in contacts) {
    var nomDeFamille = contacts[i].getFamilyName();
    if (nomDeFamille != '') {
      Logger.log("Nom de famille " + contacts[i].getFamilyName());
      var nomDeFamilleMajuscules = nomDeFamille.toUpperCase();
      var iDContact = contacts[i].getId();
      var contact = ContactsApp.getContactById(iDContact);
      contact.setFamilyName(nomDeFamilleMajuscules);
    }
  }
}

Solution

  • Only update a contact if it's not capitalized yet:

        ...
        if(nomDeFamilleMajuscules != nomDeFamille) {
            var iDContact = contacts[i].getId();
            var contact = ContactsApp.getContactById(iDContact);
            contact.setFamilyName(nomDeFamilleMajuscules);
        }
        ...
    

    You may have to run the script a few times for it to apply for all contacts, but at least it won't start over each time.

    ContactsApp.getContactById probably takes a good chunk of time, so only executing it when it's actually needed should speed it up a good bit.