見出し画像

ランダムページのパフォーマンスを改善しました

ランダムページ(https://lgtmgen.com/random/)のパフォーマンスを改善しました。

今までの方法

今まではランダム性を高めるため、ランダムな数字を生成してその数字にマッチする画像を1件取得する、というのを10回繰り返していました。

この方法だと毎回確実に異なる10の画像を取得できますが、1画面を表示するのにクエリが10回走ることになりレスポンスが遅くなってしまうことは否めませんでした。

これからの方法

擬似的なランダム表示として、ランダムな数字を生成してその数字から連続する画像10件を取得するように変更しました。そのため何回かアクセスしているとどうしても画像がかぶるケースがでますが、登録されている画像のデータ量が増えていくとその分かぶりにくくなってきます。現在の画像登録件数は400件弱なので、まあ許容されるレベルかなと考えています。

Firebaseでランダム取得する方法

FirebaseにはMySQLみたいな rand() はないため、自前で rand() 的なものを実装する必要があります。

stackoverflowに設計方針が書かれていますが、

1. データ登録時にrandamでインデックスするためのIDを埋め込む
2. randamのカラムをもとにデータを検索する

というようになります。

今回はパフォーマンスの改善のため、このstackoverflowに書かれている

Rinse & Repeat
This method is straight forward. Simply repeat the process, including selecting a new random integer each time.

This method will give you random sequences of documents without worrying about seeing the same patterns repeatedly.

The trade-off is it will be slower than the next method since it requires a separate round trip to the service for each document.

の方法から

Keep it coming
In this approach, simply increase the number in the limit to the desired documents. It's a little more complex as you might return 0..limit documents in the call. You'll then need to get the missing documents in the same manner, but with the limit reduced to only the difference. If you know there are more documents in total than the number you are asking for, you can optimize by ignoring the edge case of never getting back enough documents on the second call (but not the first).

The trade-off with this solution is in repeated sequences. While the documents are randomly ordered, if you ever end up overlapping ranges you'll see the same pattern you saw before. There are ways to mitigate this concern discussed in the next section on reseeding.

This approach is faster than 'Rinse & Repeat' as you'll be requesting all the documents in the best case a single call or worst case 2 calls.

の方法に切り替えた形です。ランダムページには10件程度だけ表示すればよいため、この方法でもそんなに大きな問題にはなりません。

sitemap.xmlの出力に対応しました

検索インデックスに乗りやすいようにsitemap.xmlを出力するようにしました。(とはいえ5ページほどですが。)

Nuxt.jsにはsitemapを生成するためのモジュールがあらかじめ公式から用意されています。

そのためほとんど手間なく設定することができました。

この記事が気に入ったらサポートをしてみませんか?