I was helping my daughter who learn coding, we started with simple javascipt, so to experience loops we illustrated that with a very simple string array sorting algorithm, the one with to simple loops i and j and a swap when item[i] > item[j].
I wanted to show her it could be different to sort a little array of 10 sort strings and and array of tens of hundreds very long strings.
I got a cat of my home directory, shuffled and parsed it as a javascript array with a little swift routine.
The cat was 25000 lines of paths accounting for 4,095,547 chars.
The whole code in Swift
import Foundation
let fileIn = URL(fileURLWithPath: "/Users/luc-olivier/Development/Learning/Mixed/SortAndFindLab/catalog_shuffled.txt")
let string = try? String(contentsOf: fileIn, encoding: String.Encoding.utf8)
guard string != nil else { assert(false, "File access issue!") }
var dataRnd = string!.components(separatedBy: "\n")
guard dataRnd != [] else { assert(false, "Data not read!") }
print("Data lines: \(dataRnd.count)")
let timeD = Date()
// Basic Sort
var swapCpt = 0
for i in 0 ..< dataRnd.count - 1 {
for j in i + 1 ..< dataRnd.count {
if dataRnd[i] > dataRnd[j] {
let temp = dataRnd[i]
dataRnd[i] = dataRnd[j]
dataRnd[j] = temp
}
}
}
//
let timeA = Date()
print(timeA.timeIntervalSince(timeD))
let fileOut = URL(fileURLWithPath: "/Users/luc-olivier/Development/Learning/Mixed/SortAndFindLab/catalog_shuffled_SwiftSorted.txt")
try dataRnd.joined(separator: "\n").write(to: fileOut, atomically: true, encoding: String.Encoding.utf8)
The elapsed time was measured with a simple Date() at start and end.
EDITED after optimization (build in mode "Release")
This sheet shows the values (2 tests for each languages).
The row named "sort()" means the test with the collection embed method sort()
With the improvement proposed by @Karl it tooks 26s against 35s.
Additionally, is there any effect from adding the following line before you start timing?
dataRnd = dataRnd.map { var x = $0; x.makeContiguousUTF8(); return x }
The reason this might help is that
components(separatedBy:)
is a Foundation method. This should Swiftify any bridged objects that were returned.
It remains enough low compared to Kotlin / Java and even Node/js.
Do you thinks there is a way to optimise compilation? I don't want change the code, in other to remain equal to other tests on other languages.