Skip to content

Commit e169805

Browse files
committed
perf(wordsoccupancy): implement caching to optimize performance
1 parent 7e2c25d commit e169805

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/strategy.jl

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,15 @@ function feelingoccupancy(imgs, border=0, bgvalue=imgs[1][1])
4747
oc * 0.93
4848
end
4949

50-
function wordsoccupancy!(wc)
50+
function wordsoccupancy!(wc, cache=(-ones(length(wc)), Vector(undef, length(wc))))
5151
words = wc.words
5252
fonts = getfonts(wc)
5353
angles = getangles(wc) ./ 180 .* π
5454
border = 1
5555
sizemax = size(wc.mask) .* (getparameter(wc, :volume) / prod(size(wc.mask))) .* 0.9
5656
check = getparameter(wc, :maxfontsize0) == :auto
5757
check && setparameter!(wc, minimum(sizemax), :maxfontsize)
58-
imgs = Vector(undef, length(words))
58+
szcache, imgs = cache
5959
for i in 1:3
6060
fontsizes = getfontsizes(wc)
6161
success = true
@@ -64,6 +64,9 @@ function wordsoccupancy!(wc)
6464
for j in ichunk:nchunk:length(words) # it is a more balance split strategy since the words is sorted by size
6565
success || break
6666
c, sz, ft, θ = words[j], fontsizes[j], fonts[j], angles[j]
67+
if szcache[j] == sz # only check the fontsize, assume the font won't change
68+
continue
69+
end
6770
img = Render.rendertext(string(c), sz, backgroundcolor=(0, 0, 0, 0), font=ft, border=border)
6871
a, b = size(img)
6972
imsz = max(a*abs(cos(θ)), b*abs(sin(θ))), max(a*abs(sin(θ)), b*abs(cos(θ)))
@@ -76,6 +79,7 @@ function wordsoccupancy!(wc)
7679
end
7780
end
7881
imgs[j] = img
82+
szcache[j] = sz
7983
end
8084
success || break
8185
end
@@ -145,6 +149,7 @@ function findscale!(wc::WC; initialscale=0, density=0.3, maxiter=5, tolerance=0.
145149
sc0 = 0.
146150
tg0 = 0.
147151
oneway_count = 1
152+
occ_cache = (-ones(length(wc)), Vector(undef, length(wc)))
148153
while true
149154
step = step + 1
150155
if step > maxiter
@@ -153,7 +158,7 @@ function findscale!(wc::WC; initialscale=0, density=0.3, maxiter=5, tolerance=0.
153158
end
154159
# cal tg1
155160
setparameter!(wc, sc1, :scale)
156-
tg1 = wordsoccupancy!(wc)
161+
tg1 = wordsoccupancy!(wc, occ_cache)
157162
dens = tg1 / area
158163
@debug "⋯scale=$(getparameter(wc, :scale)), density=$dens\t" * (dens > density ? "" : "")
159164
if tg1 > target

0 commit comments

Comments
 (0)