
在使用 Google Cloud Datastore 时,我们经常需要在实体之间建立关联。常见的做法是在结构体中存储关联实体的 Key 或者 ID。那么,哪种方式更优呢?本文将深入探讨这两种方法的优缺点,并提供一些建议,帮助您做出最佳选择。
首先,我们需要明确 Key 和 ID 的概念。
假设我们有一个 Point 结构体,它需要关联到一个 Place 实体。以下是两种存储方式的示例代码:
A) 存储 Key
type Point struct {
Place *datastore.Key
Lat float64
Lon float64
}
// 获取 Place 实体
func GetPlaceFromPoint(c context.Context, point *Point) (*Place, error) {
place := new(Place)
if err := datastore.Get(c, point.Place, place); err != nil {
return nil, err
}
return place, nil
}B) 存储 ID
type Point struct {
PlaceID int64
Lat float64
Lon float64
}
// 获取 Place 实体
func GetPlaceFromPoint(c context.Context, point *Point) (*Place, error) {
k := datastore.NewKey(c, "Place", "", point.PlaceID, nil)
place := new(Place)
if err := datastore.Get(c, k, place); err != nil {
return nil, err
}
return place, nil
}优缺点分析:
在性能方面,关键在于 Key 的创建成本。如前所述,从 Kind 和 ID 创建 Key 的成本很低,因此,在大多数情况下,存储 ID 并在需要时构建 Key 不会带来明显的性能损失。
但是,如果需要频繁地创建 Key,例如,在循环中为大量实体创建 Key,那么存储 Key 对象可能会更有效率。
以下是一些建议,帮助您选择合适的存储方式:
总结:
在结构体中存储 Key 还是 ID 取决于具体的应用场景和需求。在大多数情况下,存储 ID 并在需要时构建 Key 是一个合理的选择。但是,在某些情况下,存储 Key 对象可能会更有效率。在做出选择时,需要综合考虑存储空间、Key 创建成本、代码可读性以及灵活性等因素。
以上就是使用 Datastore Key 的两种方式:结构体中存储 Key 还是 ID?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号