I’m working on a Go project using GORM and MySQL. I need to retrieve a list of IDs from a specific entity in the database and am considering two approaches to achieve this. I’d like to know which one is more optimal in terms of performance:
- Using
Pluck
in GORM: I can use thePluck
method provided by GORM to directly extract IDs from the query results.
Example code:
var ids []int
db.Model(&YourModel{}).Pluck("id", &ids)
- Using Raw Query and
foreach
to Store IDs in a Slice: Alternatively, I can use a raw query and then manually store the retrieved IDs into a slice.
Example code:
rows, err := db.Raw("SELECT id FROM your_table").Rows()
if err != nil {
// handle error
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
if err := rows.Scan(&id); err != nil {
// handle error
}
ids = append(ids, id)
}
Question:
From a performance and efficiency standpoint, which method is better to use in this case, GORM’s Pluck
or raw query with foreach
? Are there other factors I should consider when choosing between these methods? I appreciate any advice or experiences from experts.
Thank you!
2
Answers
If your need is only to get all the ids of a given model, I would choose the
Pluck
solution to avoid memory reallocation induced by theids = append(ids, id)
statement.Getting a bunch of ids and then issuing queries using them is much less efficient (in the database) than doing all the work inside the database.
That is,
JOIN
to the other table before returning to the client.I am not familiar with GORM, so I can’t elaborate, but here is a crude fabricated example: