英文:
GORM Golang : the purpose of cloning DB instance
问题
在过去的几周里,我刚刚学习了关于GORM作为数据库ORM的知识。在查看代码后,我发现每个命令(limit、order、where、or、select等)都通过克隆当前的DB实例来返回新的实例。
这里是否有人知道克隆DB而不是使用当前实例的主要目的是什么呢?
当我使用select、where、limit、order、join等命令时,将会克隆DB实例5次。据我所知,在内存中创建对象是昂贵的。
英文:
In few pass week I just learn about GORM as the database ORM. After checking inside the code, every command (limit, order, where, or, select, etc) are returning new instance by cloning the current DB.<br>
Is there anyone here know what is the main purpose of cloning the DB instead of using the current instance?<br>
When I have command select, where, limit, order, join, that will be 5 times of cloning the DB instance. AFAIK, creating object on the memory are expensive.
答案1
得分: 5
目的是能够存储“临时”的查询实例,以便以后可以派生它们。也就是说,如果您有一些查询共享序列的一部分,您应该能够执行类似以下的操作:
q := gorm.Select(...).Limit(...).Order(...)
q1 := q.Where(...)
q2 := q.Where(...)
(这个例子只是一个大致的例子,可能甚至不能映射到我自己不使用的 GORM API。)
现在,我相信在内存中克隆不会保留很长时间的对象,与执行 SQL 查询的成本相比,并不会对性能造成太大影响,因为执行 SQL 查询需要进行网络往返...
英文:
The purpose is to be able to store "temporary" instance of your query to be able to derive them later. That is, if you have a number of queries which share the some part of the sequence, you should be able to do something like
q := gorm.Select(...).Limit(...).Order(...)
q1 := q.Where(...)
q2 := q.Where(...)
(This example is a rought example that probably doesn't even map to GORM API as I don't use it myself.)
Now, I believe that cloning objects in memory that won't be kept long doesn't hinder much performance compared to the cost of doing a SQL query, which imply a network round-trip…
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论