green-code-initiative / ecoCode-challenge

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

[iOS][Android] Use lazySequence on operations such as map or filter #36

Open PierreEc opened 1 year ago

PierreEc commented 1 year ago

Privilégier les lazysequences pour optimiser des cycles CPU inutiles

https://developer.apple.com/documentation/swift/lazysequence

Example:

(1...100_000)
    .map { $0 * $0 }
    .filter { $0.isMultiple(of: 10) }
    .first(where: { $0 > 100 } )

With lazy:

(1...100_000)
    .lazy
    .map { $0 * $0 }
    .filter { $0.isMultiple(of: 10) }
    .first(where: { $0 > 100 } )
Capture d’écran 2023-04-05 à 15 54 21
PierreEc commented 1 year ago

There is the same with kotlin with SequenceOf:

SequenceOf

PierreEc commented 1 year ago

Use lazySequence on operations such as map or filter

Platform

OS OS version Langage.
iOS/iPadOS/WatchOS/tvOS - Android - Swift / Kotlin

Main caracteristics

ID Title Category Sub-category
- Environment Optimized API

Severity / Remediation Cost

Severity Remediation Cost
Major Minor

Rule short description

Prefer lazysequences for optimize useless CPU cycles

Rule complete description

Text

Prefer lazysequences for optimize useless CPU cycles when you use operations such as map and filter

HTML

<p>Prefer lazysequences for optimize useless CPU cycles</p>
<p>
<a href="https://developer.apple.com/documentation/swift/lazysequence">Doc apple LazySequence</a>
<a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/sequence-of.html">Doc android SequenceOf</a>
</p>
<p>
<img src="https://user-images.githubusercontent.com/18304803/230103031-275bdf34-8f45-45da-abc5-8f0dd97a72a6.png" />
</p>

Implementation principle

olegoaer commented 5 months ago

This rule can now be implemented with the arrival of the Android Kotlin plugin @47tibo ;)

47tibo commented 5 months ago

Interesting way of "activating" lazy in Swift 🙂 @olegoaer we can add this rule to kotlin, but it is a bit more complex than that.

In short, it depends on the type of the operators, their order in the chain and also the size of the collection.