From 99fb8430fcb6cf967bf60442338ff22e5daa3a97 Mon Sep 17 00:00:00 2001 From: sblinch Date: Wed, 13 Mar 2019 16:30:14 -0700 Subject: [PATCH] Added book ID caching to avoid repeated calls to sha1.Sum() for the same book --- booklist/book.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/booklist/book.go b/booklist/book.go index 2b7c607c..97a63669 100644 --- a/booklist/book.go +++ b/booklist/book.go @@ -8,6 +8,11 @@ import ( "time" ) +type cachedID struct { + id string + value string +} + type Book struct { Hash string FilePath string @@ -21,18 +26,30 @@ type Book struct { Series string SeriesIndex float64 Publisher string + + seriesid cachedID + authorid cachedID } func (b *Book) ID() string { return b.Hash[:10] } +func (b *Book) cachedIDStr(cached *cachedID, value string) string { + if len(cached.id)==0 || value != cached.value { + cached.value = value + cached.id = fmt.Sprintf("%x", sha1.Sum([]byte(value)))[:10] + } + + return cached.id +} + func (b *Book) AuthorID() string { - return fmt.Sprintf("%x", sha1.Sum([]byte(b.Author)))[:10] + return b.cachedIDStr(&b.authorid,b.Author) } func (b *Book) SeriesID() string { - return fmt.Sprintf("%x", sha1.Sum([]byte(b.Series)))[:10] + return b.cachedIDStr(&b.seriesid,b.Series) } func (b *Book) FileType() string {