Skip to content

Commit c1f7e49

Browse files
committed
Merge pull request #18 from nshintio/source_dateFormatter
Date Formatter post
2 parents fdc7f4c + 741ebaa commit c1f7e49

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
layout: post
3+
title: "Using sql as date formatter"
4+
date: 2015-08-04 20:50:51 +0200
5+
comments: false
6+
author: marcin
7+
categories:
8+
---
9+
10+
This post is a quick update to [Vombat's blog post](http://vombat.tumblr.com/post/60530544401/date-parsing-performance-on-ios-nsdateformatter) about using SQL instead of `NSDateFormatter` when it comes to parsing dates in your project. If you don't read it yet, I will highly recommend to do it now. This time we will use Swift to make same measurements.
11+
12+
TL;DR:
13+
14+
You can use sql database function `strftime` to get UNIX time from e.g.: ISO8061 date string.
15+
16+
Here is the magic function:
17+
18+
```objc
19+
+ (NSArray *)parseDatesUsingStringArray:(NSArray *)stringsArray
20+
{
21+
sqlite3 *db = NULL;
22+
sqlite3_open(":memory:", &db);
23+
24+
sqlite3_stmt *statement = NULL;
25+
sqlite3_prepare_v2(db, "SELECT strftime('%s', ?);", -1, &statement, NULL);
26+
27+
NSMutableArray *datesArray = [NSMutableArray array];
28+
29+
for (NSInteger i = 0; i < stringsArray.count; i++)
30+
{
31+
NSString *dateString = stringsArray[i];
32+
33+
sqlite3_bind_text(statement, 1, [dateString UTF8String], -1, SQLITE_STATIC);
34+
sqlite3_step(statement);
35+
36+
kTimeStamp value = sqlite3_column_int64(statement, 0);
37+
NSDate *date = [NSDate dateWithTimeIntervalSince1970:value];
38+
39+
[datesArray addObject:date];
40+
41+
sqlite3_clear_bindings(statement);
42+
sqlite3_reset(statement);
43+
}
44+
45+
sqlite3_close(db);
46+
47+
return datesArray;
48+
}
49+
```
50+
51+
We will use it to replace standard parsing method like this:
52+
53+
```swift
54+
var datesFromNSDateFormatter:[NSDate] = []
55+
56+
for string in stringsArray {
57+
datesFromNSDateFormatter.append(NSDateFormatter.dateFromISOString(string))
58+
}
59+
```
60+
61+
I did some measurements using iPhone 5S with iOS8.2 in release configuration running exactly same amount of data (One Milion strings with ISO8601 date)
62+
63+
And here are the results:
64+
65+
```
66+
Time elapsed for NSDateFromatter parsing: 73.7988719940186 s
67+
Time elapsed for SQLDateFormatter parsing: 8.51147103309631 s
68+
```
69+
70+
So using SQL to format string into date is pretty fast but acutally slower than objC version (But still at least 10time faster than regular method) So what about Swift?. Nothing really changed, overall results show faster computation but I'm using better CPU so `NSDateFormatter` is still very very slow... If you like it, sample source code is available on <a href="https://github.com/noxytrux/DateFormatter">Github</a>
71+
72+

0 commit comments

Comments
 (0)