Skip to content

Commit cfc354f

Browse files
committed
2 parents 382a402 + e15e6b6 commit cfc354f

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 Wouter Hennen
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# swift-csv
2+
This package provides iterators to parse CSV files from Swift, with a focus on performance and efficiency.
3+
The provided file is read in a streaming way, and is not loaded in memory as a whole. This reduces memory usages drastically, especially for large files.
4+
5+
Three AsyncSequences are provided: `AsyncCodableCSVIterator`, `AsyncRawCSVIterator` and `AsyncRawAsDictCSVIterator`.
6+
7+
### Features
8+
- Asynchronous reading of CSV files, line by line.
9+
- Decode using Codable types.
10+
- Process each row manually as a list of strings or a key-value dictionary.
11+
- Support for files with or without headers.
12+
- Error handling, option to skip invalid rows.
13+
- Support for custom delimiters, escape characters and file encodings.
14+
- Support for local and remote CSV files.
15+
16+
### Examples
17+
Parse the CSV file at once, decode using `Codable` types:
18+
```swift
19+
let ratings: [Rating] = try await Task.detached {
20+
try await AsyncCodableCSVIterator(url: ratingsURL)
21+
.reduce(into: []) { $0.append($1) }
22+
}.value
23+
```
24+
25+
Parse the CSV file row by row, get list of strings for each row:
26+
```swift
27+
let reader = try await AsyncRawCSVIterator(url: ratingsURL, hasHeaders: true, skipInvalidRows: false)
28+
for try await row in reader {
29+
// process...
30+
}
31+
```
32+
33+
Parse the CSV file row by row, get a dict of key-value strings for each row:
34+
```swift
35+
let reader = try await AsyncRawAsDictCSVIterator(url: ratingsURL)
36+
for try await row in reader {
37+
// process...
38+
}
39+
```
40+
41+
### Notes about Performance
42+
One of the goals of this package is to provide a fast and efficient way to parse CSV files, while still using regular Swift.
43+
This isn't always an easy task, as one can quickly fall into performance traps. Making small changes to how the API is used can drastically improve the performance of your app:
44+
45+
- When possible, do **NOT** use the API on the Main Actor. Internally, the API is using [`URL.resourceBytes`](https://developer.apple.com/documentation/foundation/url/3767316-resourcebytes) which runs off the Main Actor. If the iterator is used on the main actor, a context switch will happen for **each** row, making the iteration much slower. In my own testings, this made the parsing of a file 6 times slower. Instead, use a Task.detached when iterating over the file. When parsing, no context switches will happen.
46+
```swift
47+
let ratings: [Rating] = try await Task.detached {
48+
try await AsyncCodableCSVIterator(url: ratingsURL)
49+
.reduce(into: []) { $0.append($1) }
50+
}
51+
}.value
52+
```
53+
- When decoding with `AsyncCodableCSVIterator`, try using Int-based CodingKeys instead of String-based CodingKeys. This shouldn't be a problem, as a CSV file contains ordered data. Decoding the data is much faster using indexes rather than a dictionary lookup. In tests, using Int-based CodingKeys results in a approx. 30% faster decoding.
54+
```swift
55+
struct Rating: Codable {
56+
let id: String,
57+
movieID: String,
58+
ratingValue: Int,
59+
userID: String
60+
61+
enum CodingKeys: Int, CodingKey {
62+
case id
63+
case movieID
64+
case ratingValue
65+
case userID
66+
}
67+
}
68+
```
69+
### Benchmarks
70+
Some benchmarks were performed to evaluate the performance of the API.
71+
The benchmark will parse a 616MB CSV file with 11078167 rows and 4 columns. The AsyncCodableCSVIterator runs will decode the data into the `Rating` type. The other will not process the strings any further.
72+
73+
| | Swift 5.10 | Swift 6.0 (2024-05-26) |
74+
|----------|----------|----------|
75+
| AsyncRawCSVIterator | 6.88s | 5.68s |
76+
| AsyncCodableCSVIterator, Int CodingKeys | 10.41s | 7.27s |
77+
| AsyncRawAsDictCSVIterator | 10.66s | 9.14s |
78+
| AsyncCodableCSVIterator, String CodingKeys | 14.92s | 11.14s |

0 commit comments

Comments
 (0)