improved list performance (1000 posts -> 118ms). #5

This commit is contained in:
Niko Abeler 2022-08-17 22:21:44 +02:00
parent e4c0550205
commit 54d319e8d7
2 changed files with 42 additions and 12 deletions

29
user.go
View File

@ -65,24 +65,31 @@ func (user User) Posts() ([]Post, error) {
}
}
// sort posts by date
sort.Slice(posts, func(i, j int) bool {
_, markdownData_i := posts[i].MarkdownData()
_, markdownData_j := posts[j].MarkdownData()
type PostWithDate struct {
post Post
date time.Time
}
date_i, err := time.Parse(time.RFC1123Z, markdownData_i.Date)
postDates := make([]PostWithDate, len(posts))
for i, post := range posts {
_, meta := post.MarkdownData()
date, err := time.Parse(time.RFC1123Z, meta.Date)
if err != nil {
// invalid date -> use 1970-01-01
date_i = time.Time{}
date = time.Time{}
}
date_j, err := time.Parse(time.RFC1123Z, markdownData_j.Date)
if err != nil {
// invalid date -> use 1970-01-01
date_j = time.Time{}
postDates[i] = PostWithDate{post: post, date: date}
}
return date_i.After(date_j)
// sort posts by date
sort.Slice(postDates, func(i, j int) bool {
return postDates[i].date.After(postDates[j].date)
})
for i, post := range postDates {
posts[i] = post.post
}
return posts, nil
}

View File

@ -202,6 +202,29 @@ func TestPostsSortedByPublishingDateLatestFirst(t *testing.T) {
}
}
func TestPostsSortedByPublishingDateLatestFirst2(t *testing.T) {
user := getTestUser()
// Create a new post
posts := []*owl.Post{}
for i := 59; i >= 0; i-- {
post, _ := user.CreateNewPost("testpost")
content := "---\n"
content += "title: Test Post\n"
content += fmt.Sprintf("date: Wed, 17 Aug 2022 10:%02d:02 +0000\n", i)
content += "---\n"
content += "This is a test"
os.WriteFile(post.ContentFile(), []byte(content), 0644)
posts = append(posts, &post)
}
retPosts, _ := user.Posts()
for i, p := range retPosts {
if p.Id() != posts[i].Id() {
t.Error("Wrong Id, Got: " + p.Id())
}
}
}
func TestPostsSortedByPublishingDateBrokenAtBottom(t *testing.T) {
user := getTestUser()
// Create a new post