green-code-initiative / ecoCode-challenge

Emboard in the hackhatons serie for improving ecoCode
4 stars 5 forks source link

[Hackathon 2024][Niobium][IOS] Avoid useless multiple instantiations of formater in a loop #106

Open raphaelbnpp opened 5 months ago

raphaelbnpp commented 5 months ago

Rule title

Avoid useless multiple instantiations of formater in a loop

Language and platform

Swift - IOS

Rule description

What does your rule do? Why is this a green coding issue?

My rule checks if there is any formater instantiation inside a loop in the code. We should rather initiate it upstream the loop to avoid multiple instantiation that are useless.

var date = Date()

for _ in 1...1_000_000 {
    let formater = DateFormatter()
    formater.dateFormat = "dd/MM/yyyy"
    let result = formater.string(from: date)
}

Instead, the following code can be proposed:

var date = Date()
let formater = DateFormatter()

for _ in 1...1_000_000 {
    formater.dateFormat = "dd/MM/yyyy"
    let result = formater.string(from: date)
}
var date = Date()

for _ in 1...1_000_000 {
    let result = date.formatted(date: .numeric, time: .omitted)
}

Rule short description

Avoid useless multiple instantiations of formater in a loop.

Rule justification

Analyse of the duration of execution by CPU usage. By taking the triggered and the two untrigerred codes and analyzing the execution time with the use of the CPU we obtain the following results. These measures were done with Instruments.

We can observe that the triggered code takes much more time (24s) to be executed than the two other suggested code that takes a similar time to run (1.5s and 1.7s).

Severity / Remediation Cost

Severity: Major (depends of on the quantity of iteration of the loop)

Remediation: Medium (formater should not be declared inside a loop.)

Implementation principle

In any loop, ensure that no formater is instantiated.