Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

79
Visualizações
Swift concurrent operation slower 2x times

I have a large JSON array that I need to save to Realm, the problem is that this operation lasts around 45 seconds and that's too long. I tried running the save operation concurrently for each element in JSON array like this:

for element in jsonArray { // jsonArray has about 25 elements
  DispatchQueue.global(qos: .userInitiated).async {
    let realm = try! Realm()
    let savedObject = realm.objects(MyObject.self).filter("name == '\(element.name)'")

    for subElement in element { // element is an array that has around 1000 elements
      let myModel = MyModel(initWith: subElement) // MyModel initialization is a simple light weight process that copies values from one model to another
      savedObject.models.append(myModel)
    }

  }
}

When I try to run the same code but with DispatchQueue.main.async it finished around 2x faster even though it's not concurrent. I also tried running the code above with quality of service .userInteractive but it is the same speed.

When I run this code CPU utilization is about 30%, and memory about 45 MB. Is it possible to speed up this operation or I reached dead end?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

  1. The entire loop should be inside the DispatchQueue.global(qos: .userInitiated).async block.
  2. As documented on the Realm website:

    Realm write operations are synchronous and blocking, not asynchronous. If thread A starts a write operation, then thread B starts a write operation on the same Realm before thread A is finished, thread A must finish and commit its transaction before thread B’s write operation takes place. Write operations always refresh automatically on beginWrite(), so no race condition is created by overlapping writes.

    This means you won't get any benefit by trying to write in multiple threads.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda