Skip to content

Instantly share code, notes, and snippets.

@draveness
Last active October 14, 2020 07:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draveness/8e714b61a1d20c836fd9ac8fa6553cdd to your computer and use it in GitHub Desktop.
Save draveness/8e714b61a1d20c836fd9ac8fa6553cdd to your computer and use it in GitHub Desktop.
Benchmark Foreign Key
package main
import (
"testing"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Post struct {
ID int64
AuthorID int64
}
type Author struct {
ID int64
}
type ForeignKeyPost struct {
ID int64
AuthorID int64
}
var conn *gorm.DB
func init() {
var err error
conn, err = gorm.Open("mysql", "root:@tcp(localhost:3306)/fk_dev?parseTime=true")
if err != nil {
panic(err)
}
conn.AutoMigrate(&Post{}).
AutoMigrate(&Author{}).
AutoMigrate(&ForeignKeyPost{})
conn.Model(&ForeignKeyPost{}).AddForeignKey("author_id", "authors(id)", "RESTRICT", "RESTRICT")
conn.Create(&Author{ID: 1})
}
func BenchmarkBaseline(b *testing.B) {
for i := 0; i < b.N; i++ {
if err := conn.Create(&Post{AuthorID: 1}).Error; err != nil {
panic(err)
}
}
}
func BenchmarkForeignKey(b *testing.B) {
for i := 0; i < b.N; i++ {
if err := conn.Create(&ForeignKeyPost{AuthorID: 1}).Error; err != nil {
panic(err)
}
}
}
@draveness
Copy link
Author

BenchmarkBaseline-8     	    3770	    309503 ns/op
BenchmarkForeignKey-8   	    3331	    317162 ns/op

BenchmarkBaseline-8     	    3192	    315506 ns/op
BenchmarkForeignKey-8   	    3381	    315577 ns/op

BenchmarkBaseline-8     	    3298	    312761 ns/op
BenchmarkForeignKey-8   	    3829	    345342 ns/op

BenchmarkBaseline-8     	    3753	    291642 ns/op
BenchmarkForeignKey-8   	    3948	    325239 ns/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment