malcommac / SwiftDate

🐔 Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.
MIT License
7.61k stars 767 forks source link

Date.toFormat(String) function takes too long to execute in loop #817

Open kylechandev opened 1 year ago

kylechandev commented 1 year ago

Code sample:

let s = Date.nowMilliStamp
let date = Date.now
for _ in 0 ..< 980 {
    // let _ = Date.from(millis: Date.nowMilliStamp) // 6ms
    // let _ = Date.from(millis: a) // 5ms
    let s = Date.nowMilliStamp
    let _ = date.toFormat("yyyy-MM-dd HH:mm") // 3168ms
    let e = Date.nowMilliStamp
    print("toFormat cost time:\(e - s)ms")
}
let e = Date.nowMilliStamp
print("time cost:\(e - s)ms")

In this case, Continuously calling the toFormat function 980 times takes 3168ms, it's too long.

I found that when I only call the toFormat function once, it only takes 1ms, and the more loop times, the execution time of the toFormat function will be higher and higher.

Taking execution 980 times as an example, the time-consuming of each call toFormat has been continuously increased from 1ms to a maximum of 8ms, so the execution time of the whole function becomes very high.

I'm very confused, can someone help me analyze what is causing this? Or is this a bug of SwiftDate? Thank you so much!