Post

Replies

Boosts

Views

Activity

Reply to Object vs Int array subscript (get and set) is 250 times too slow
I just discovered that this is a known and unresolved issue when the same array appears on both sides of the equal sign, such as when swapping elements of an array. An unnecessary copy-on-write of the array happens each time. Breaking it into 4 lines also fixes the problem: let val1 = arr[index1] let val2 = arr[index2] arr[index1] = val2 arr[index2] = val1 https://github.com/apple/swift/issues/56451
Topic: Programming Languages SubTopic: Swift Tags:
Mar ’23
Reply to Object vs Int array subscript (get and set) is 250 times too slow
Thank you. I hadn't noticed arr.swapAt() in the Array API. For completeness, here is how the performance of various array swaps compares when run with swift -O using arrRef and swapAt : [Int] - 0.8msec / [Obj] - 3.5msec using arrRef and 1 pair : [Int] - 0.4msec / [Obj] - 3.2msec using arrRef and 2 pairs: [Int] - 0.5msec / [Obj] - 5.6msec using arrRef and verbose: [Int] - 0.4msec / [Obj] - 5.6msec using self.arr and swapAt : [Int] - 1.6msec / [Obj] - 3.8msec using self.arr and 1 pair : [Int] - 159.0msec / [Obj] - 15600.0msec using self.arr and 2 pairs: [Int] - 1.5msec / [Obj] - 8.2msec using self.arr and verbose: [Int] - 1.4msec / [Obj] - 6.9msec Sample code with arrRef:    func swapsTestUsingReference(_ arrRef: inout [T], _ repeats: Int) {     let size = arrRef.count     for i in 0..<repeats {       let index1 = i % size       let index2 = (i + 1) % size        // using swapAt       //arrRef.swapAt(index1, index2)        // using 1 pair       //(arrRef[index1], arrRef[index2]) = (arrRef[index2], arrRef[index1])        // using 2 pairs       // let (v1, v2) = (arrRef[index1], arrRef[index2]);       // (arrRef[index2], arrRef[index1]) = (v1, v2); // using verbose       //let v1 = arrRef[index1]       //let v2 = arrRef[index2]       //arrRef[index2] = v1       //arrRef[index1] = v2     }   }
Topic: Programming Languages SubTopic: Swift Tags:
Mar ’23