Git Product home page Git Product logo

strftimeformatter's Introduction

Overview

STRFTimeFormatter is a simple class that encapsulates the strftime_l(3) and strptime_l(3) functions in an interface that replicates that of NSDateFormatter. This class is to be used to convert machine generated dates in an efficient manner as mentioned in issue 9 of objc.io (see the section on Parsing Machine Input).

Installation

Installation is best done via cocoapods.

Podfile

pod 'STRFTimeFormatter'

Usage

STRFTimeFormatter replicates the convenience functions of the NSDateFormatter class:

- (NSDate *)dateFromString:(NSString *)string;
- (NSString *)stringFromDate:(NSDate *)date;

The only optional setup is to change the formatString used by the strftime_l(3) and strptime_l(3) functions. See the strftime(3) man page for possible format specifiers. The default is %Y-%m-%dT%H:%M:%S%z, which corresponds to a string format such as 2014-02-18T12:42:07+0000.

STRFTimeFormatter is not a subclass of NSFormatter, for two reasons:

  • It should be cheap to allocate an instance.
  • Laziness.

The Point

strptime_l(3) is a lot faster than -[NSDateFormatter dateFromString:], but it's a pain to use. STRFTimeFormatter gives you the huge performance bump when dealing fixed format date strings, but without the hassle of dropping into C libraries all the time (or having to put #import <xlocale.h> everywhere - how ugly).

Here's the proof:

#import <Foundation/Foundation.h>
#import <xlocale.h>

#define LOG_SAMPLES

void startTimer(NSDate **timer);
void finishTimer(NSDate *timer, NSString *message);

int main(int argc, char *argv[])
{
    @autoreleasepool {
        
        NSUInteger numberOfDatesToCreate = 604800;
        NSLog(@"Creating %llu date strings.", (unsigned long long)numberOfDatesToCreate);
        
        NSDate *timer;
        
        // string format to be used by strftime_l and strptime_l
        const char *formatString = "%Y-%m-%dT%H:%M:%S%z";
        
        // date formatter to be used
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
        [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
        
        NSMutableArray *strfStrings = [[NSMutableArray alloc] init];
        NSMutableArray *formatterStrings = [[NSMutableArray alloc] init];
        
        startTimer(&timer);
        
        for (NSUInteger i = 0; i < numberOfDatesToCreate; i++) {
            
            @autoreleasepool {
                
                // create the date anyway, lets keep the comparison fair :)
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:(1392595200 + i)];
                
                time_t timeInterval = [date timeIntervalSince1970];
                struct tm time = *localtime(&timeInterval);
                char buffer[80];
                
                strftime_l(buffer, sizeof(buffer), formatString, &time, NULL);
                NSString *dateString = [NSString stringWithCString:buffer encoding:NSASCIIStringEncoding];
                
#ifdef LOG_SAMPLES
                if (i % 86400 == 0) {
                    NSLog(@"Sample: %@", dateString);
                }
#endif
                
                [strfStrings addObject:dateString];
            }
        }
        
        finishTimer(timer, @"Created date strings using strftime_l(3)");
        startTimer(&timer);
        
        for (NSUInteger i = 0; i < numberOfDatesToCreate; i++) {
            
            @autoreleasepool {
                
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:(1392595200 + i)];
                NSString *dateString = [dateFormatter stringFromDate:date];
                
#ifdef LOG_SAMPLES
                if (i % 86400 == 0) {
                    NSLog(@"Sample: %@", dateString);
                }
#endif
                
                [formatterStrings addObject:dateString];
            }
        }
        
        finishTimer(timer, @"Created date strings using NSDateFormatter");
        
        NSLog(@"Parsing %llu date strings.", (unsigned long long)numberOfDatesToCreate);
        
        startTimer(&timer);
        
        for (NSUInteger i = 0; i < numberOfDatesToCreate; i++) {
            
            NSString *dateString = strfStrings[i];
            
            struct tm time;
            strptime_l([dateString cStringUsingEncoding:NSASCIIStringEncoding], formatString, &time, NULL);
            time_t timeInterval = mktime(&time);
            
            // create the date anyway, lets keep the comparison fair :)
            __unused NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
            
#ifdef LOG_SAMPLES
            if (i % 86400 == 0) {
                NSLog(@"Sample: %@", date);
            }
#endif
        }
        
        finishTimer(timer, @"Parsed date strings using strptime_l(3)");
        startTimer(&timer);
        
        for (NSUInteger i = 0; i < numberOfDatesToCreate; i++) {
            
            NSString *dateString = formatterStrings[i];
            __unused NSDate *date = [dateFormatter dateFromString:dateString];
            
#ifdef LOG_SAMPLES
            if (i % 86400 == 0) {
                NSLog(@"Sample: %@", date);
            }
#endif
        }
        
        finishTimer(timer, @"Parsed date strings using NSDateFormatter");
    }
}

void startTimer(NSDate **timer)
{
    *timer = [NSDate date];
}

void finishTimer(NSDate *timer, NSString *message)
{
    NSTimeInterval interval = -[timer timeIntervalSinceNow];
    NSLog(@"%@ -- %g seconds", message, interval);
}

strftimeformatter's People

Contributors

ellneal avatar alexpezzi avatar brunophilipe avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.