yogita1203 / PracticeProject

0 stars 0 forks source link

Improve performance of reversing and filtering of users list #4

Open nets-dev opened 3 years ago

nets-dev commented 3 years ago

This example is very small and performance gain is negligible. However, for the sake of discussion, how can you improve performance of current filter and reverse implementation.

Right now, the list iterated twice. One for sorting and another for filtering.

yogita1203 commented 3 years ago

Here is the snippet using single loop.

let usersList = try JSONDecoder.init().decode([User].self, from: data)
                    var sortedFilteredList : [User] = [User]()
                    for user in usersList.reversed() {
                        if(user.id != Int(excludingUserWithID!))
                        {
                        sortedFilteredList.append(user)
                        }
                    }
yogita1203 commented 3 years ago

@nets-dev @sagarbheda

We can reverse array in one loop using this logic.

           var sortedFilteredList : [User] = [User]()

                for index in stride(from: usersList.count, to: 0, by: -1)
                {
                    if(usersList[index - 1].id !=  (Int(excludingUserWithID!)))
                    {
                        sortedFilteredList.append(usersList[index - 1])
                    }
                }
yogita1203 commented 3 years ago

@nets-dev @sagarbheda I have used @StateObject instead of @EnvironmentObject.

Here is my commit id for this changes : https://github.com/yogita1203/PracticeProject/commit/aab412818224bdff852fbca262192adc3006ab1c