Jason Krowl
Jason Krowl

Reputation: 114

How to transform this statement for better performance

I have a very bad performance while building (indexing takes 5 - 7 minutes) since I added following lines into my code.

var valuesToPassToDetailViewController = [[String:[String: Any]]]()
var dict = [String:[String: Any]]()
dict = [title as! String:["title":title as! String, "valueD":postValue["value"] ?? "", "valueD":postValue["value"] ?? "","valueD":postValue["value"] ?? "","valueD": postValue["value"] ?? "","valueD": postValue["value"] ?? "","valueD":postValue["value"] ?? "","valueD":postValue["value"] ?? "" ,"valueD": postValue["value"] ?? "", "valueD": postValue["value"] ?? ""]]
self.valuesToPassToDetailViewController.append(dict)

Please have in mind that valueD is replacement for Key which is of course with different key values and value is replacement same as one above.

Please help me with this. Thanks for every respond.

Upvotes: 0

Views: 61

Answers (1)

ingconti
ingconti

Reputation: 11646

(Apart from being a bad code practice) You write a code that Swift compiler will processes badly, due to a lot of nesting of literals. (happens also in other piece of code.) Simpler solution:

As You are repeatingly using the same value:

let nonNullValue = postValue["value"] ?? ""

dict = [title as! String : ["title":title,
                            "valueD": nonNullValue,
                            "valueD": nonNullValue,
                            "valueD": nonNullValue,
                            "valueD": nonNullValue,
                            "valueD": nonNullValue,
                            "valueD": nonNullValue,
                            "valueD": nonNullValue ,
                            "valueD": nonNullValue,
                            "valueD": nonNullValue]]

will do the job.

If I am allowed, some coding notes:

  • use a var for repeating values, doing so not only makes compiler happy, but also it is in general FASTER (especially if You use a.b.c.d() that will produce a call/return.. )

  • do not pass generic structures between controls, when read/downloaded, create your class/struct and pass them around.

  • is better to add to dict dynamically, and will be easy if You have to read data for example from disk/network.

Hope this can help.

another suggestion:

pass to typealias in this way:

typealias Dict = [[String:[String: Any]]]

so You can write:

    var valuesToPassToDetailViewController2 = Dict()

counter-test:

    var valuesToPassToDetailViewController = [[String:[String: Any]]]()
    var valuesToPassToDetailViewController2 = Dict()

    valuesToPassToDetailViewController2 = valuesToPassToDetailViewController

Upvotes: 1

Related Questions