Uploaded image for project: 'Swift'
  1. Swift
  2. SR-4937

DispatchQueue.sync much slower than dispatch_queue_sync due to unnecessary allocations

    XMLWordPrintable

    Details

      Description

      Swift program

      This Swift program

      import Foundation
      
      func main() -> Int {
          let q = DispatchQueue(label: "q")
      
          let iterations = 100000000
      
          for _ in 0..<iterations {
              q.sync {}
          }
          return 0
      }
      
      _ = main()
      

      compiled with swiftc -O test_dispatch_sync_slow.swift takes about 14s to run on my machine (with Swift 3.1 and swift-4.0-DEVELOPMENT-SNAPSHOT-2017-05-17)

      C program

      This C program

      #include <dispatch/dispatch.h>
      
      int main() {
          dispatch_queue_t q = dispatch_queue_create("q", DISPATCH_QUEUE_SERIAL);
      
          int iterations = 100000000;
      
          for (int i=0; i<iterations; i++) {
              dispatch_sync(q, ^{});
          }
      
          dispatch_release(q);
          return 0;
      }
      

      however (which should be exactly the same) only takes about 2s to execute (compiled with clang -O3 test_dispatch_sync_fast.c -o test_dispatch_sync_fast).

      Difference

      The difference is that the Swift program spends most of the time calling Block_copy and Block_release which aren't necessary for a synchronous dispatch... See screenshot.

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              jw Johannes Weiss
            • Votes:
              1 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated: