Search code examples
iosnsdatensdateformatterfoundation

NSDateFormatter expense


How expensive creation/modification of DateFormatters is? Is it cheaper to create 4 slightly different DateFormatters or modify a single DateFormatter?

I vaguely remember that modifying DateFormatters was as expensive as modifying GL Context (that is: very).

There is a dated discussion on the topic Why is allocating or initializing NSDateFormatter considered "expensive"?


Solution

  • func testPerformanceExampleUpdateFormat() {
        self.measure {
            (0...1_000).forEach { _ in
                let df = DateFormatter()
                df.dateFormat = "MMM yyyy"
                let formattedDate1 = df.string(from: Date())
                df.dateFormat = "MM/dd/yyyy"
                let formattedDate2 = df.string(from: Date())
            }
        }
    }
    
    func testPerformanceExampleNewInstance() {
        self.measure {
            (0...1_000).forEach { _ in
                let df1 = DateFormatter()
                df1.dateFormat = "MMM yyyy"
                let df2 = DateFormatter()
                df2.dateFormat = "MM/dd/yyyy"
                let formattedDate1 = df1.string(from: Date())
                let formattedDate2 = df2.string(from: Date())
            }
        }
    }
    
    • Result time when updating a format 1 000 times: 0.0896 s.

    • Result time when creating a new instance 1 000 times: 0.138 s.

    How expensive is a type?

    func testPerformanceExample() {
        self.measure {
                        (0...1_000).forEach { _ in
                let int = DateFormatter()
            }
        }
    }
    

    The result time is 0.0017 s. for 1 000 instances of DateFormat

    Let's compare it to other types:

    0.000883 s. for 1 000 instances of Int; // let int = 2

    0.000814 s. for 1 000 instances of String; // let str = String("Hello")

    0.00118 s. for 1 000 instances of Date; // let date = Date()

    0.0784 s. for 1 000 instances of UITableViewController; let vc = UITableViewController()

    0.246 s. for 1 000 instances of UITableView; // let tv = UITableView()

    Is it expensive?