Help us understand the problem. What is going on with this article?

Extension でのインスタンスの取り扱いに注意する

今回は以前書いた下記の記事で、アプリのパフォーマンスをさらにあげるための方法を簡単に紹介したいと思います。

https://qiita.com/yum_fishing/items/cee4d2ed3561bfae7fd7

改善方法

整数に3文字区切りのカンマをつけた文字列を返すプロパティを以前は下記のような形で書きました。

extension UInt {
    var withCommaString: String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        numberFormatter.groupingSeparator = ","
        numberFormatter.groupingSize = 3

        return numberFormatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
}

仮に、下記のようなメソッドを用意して 10,000 件のデータをコンバートした場合は、同じ NumberFormatter() インスタンス が 10,000 件生成されることになります。特に Formatter はインスタンスを生成するコストは高いのでなるべくインスタンスを使いまわした方がパフォーマンスは向上します。

func getPriceList(source: [UInt]) -> String {
    return source.map { $0.withCommaString }
}

そして修正したコードがこちらになります。static let を用いることで遅延初期化され、呼び出し毎に初期化されることがなくなります。

extension UInt {
    private static let numberFormatter: NumberFormatter = {
        return NumberFormatter()
    }()
    var withCommaString: String {
        UInt.numberFormatter.numberStyle = .decimal
        UInt.numberFormatter.groupingSeparator = ","
        UInt.numberFormatter.groupingSize = 3

        return UInt.numberFormatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
}

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした