Created
          December 1, 2017 11:04 
        
      - 
      
- 
        Save nicklockwood/a99f73c22cac4249a8e9ba2fdb93e638 to your computer and use it in GitHub Desktop. 
    Thread-safe cache implementation benchmark
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | var cache = [Int: Int]() | |
| let queue = DispatchQueue(label: "cacheQueue", attributes: .concurrent) | |
| let iterations = 100000 | |
| // In the first run, cache is empty so we're writing each time | |
| do { | |
| let start = CFAbsoluteTimeGetCurrent() | |
| for i in 0 ... iterations { | |
| var exists = false | |
| queue.sync { | |
| if cache[i] != nil { | |
| exists = true | |
| } | |
| } | |
| if !exists { | |
| queue.async(flags: .barrier) { | |
| cache[i] = i | |
| } | |
| } | |
| } | |
| queue.sync { | |
| print("read + write:", CFAbsoluteTimeGetCurrent() - start) | |
| } | |
| } | |
| // In the second run, cache is full so we're only reading | |
| do { | |
| let start = CFAbsoluteTimeGetCurrent() | |
| for i in 0 ... iterations { | |
| var exists = false | |
| queue.sync { | |
| if cache[i] != nil { | |
| exists = true | |
| } | |
| } | |
| if !exists { | |
| preconditionFailure() | |
| } | |
| } | |
| queue.sync { | |
| print("reading only:", CFAbsoluteTimeGetCurrent() - start) | |
| } | |
| } | |
| // serial queue, sync read + write, | |
| // read + write: 0.0808299779891968 | |
| // reading only: 0.0366910099983215 | |
| // serial queue, sync read, async write | |
| // read + write: 1.15412402153015 | |
| // reading only: 0.0387730002403259 | |
| // concurrent queue, sync read, async write with barrier | |
| // read + write: 1.31403398513794 | |
| // reading only: 0.0410760045051575 | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Update: it's even faster to use
os_unfair_lockinstead ofDispatchQueue: