0

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"?

Mayank
  • 315
  • 2
  • 13
Anton Tropashko
  • 5,486
  • 5
  • 41
  • 66
  • 1
    It is rather expensive. It's not really about not creating many formatters. You only have to avoid creating them on the fly, e.g. not creating a formatter for every value to be formatted. – Sulthan Feb 03 '20 at 08:22

2 Answers2

1

The bad thing about NSDateFormatter is the cost to create a new instance or set format and locale. Actually these actions are one of the most slow operations on iOS SDK and you really must avoid it. Read this article to understand more about expensive objects like NSDateFormatter

Mayank
  • 315
  • 2
  • 13
1
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?

Community
  • 1
  • 1
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93