mirror of
https://github.com/discourse/discourse.git
synced 2025-02-16 10:14:52 -06:00
PERF: reduce workload when optimizing images
Previously, we would initialize an ImageOptim object each time we resize. This object init is mega expensive (170ms on a VERY fast machine): ``` [1] pry(main)> Benchmark.measure { FileHelper.image_optim } => #<Benchmark::Tms:0x00007f55440c1de0 @cstime=0.055742, @cutime=0.141031, @label="", @real=0.17165619300794788, @stime=0.0002750000000000252, @total=0.19890400000000008, @utime=0.0018560000000000798> ``` This happens cause during init it hunts for all the right binaries and sets up internals. We now memoize this object to avoid a huge amount of pointless work.
This commit is contained in:
parent
f73fe36772
commit
4232d32699
@ -83,28 +83,43 @@ class FileHelper
|
||||
end
|
||||
|
||||
def self.optimize_image!(filename, allow_pngquant: false)
|
||||
pngquant_options = false
|
||||
if allow_pngquant
|
||||
pngquant_options = { allow_lossy: true }
|
||||
end
|
||||
|
||||
ImageOptim.new(
|
||||
# GLOBAL
|
||||
timeout: 15,
|
||||
skip_missing_workers: true,
|
||||
# PNG
|
||||
optipng: { level: 2, strip: SiteSetting.strip_image_metadata },
|
||||
advpng: false,
|
||||
pngcrush: false,
|
||||
pngout: false,
|
||||
pngquant: pngquant_options,
|
||||
# JPG
|
||||
jpegoptim: { strip: SiteSetting.strip_image_metadata ? "all" : "none" },
|
||||
jpegtran: false,
|
||||
jpegrecompress: false,
|
||||
image_optim(
|
||||
allow_pngquant: allow_pngquant,
|
||||
strip_image_metadata: SiteSetting.strip_image_metadata
|
||||
).optimize_image!(filename)
|
||||
end
|
||||
|
||||
def self.image_optim(allow_pngquant: false, strip_image_metadata: true)
|
||||
# memoization is critical, initializing an ImageOptim object is very expensive
|
||||
# sometimes up to 200ms searching for binaries and looking at versions
|
||||
memoize("image_optim", allow_pngquant, strip_image_metadata) do
|
||||
pngquant_options = false
|
||||
if allow_pngquant
|
||||
pngquant_options = { allow_lossy: true }
|
||||
end
|
||||
|
||||
ImageOptim.new(
|
||||
# GLOBAL
|
||||
timeout: 15,
|
||||
skip_missing_workers: true,
|
||||
# PNG
|
||||
optipng: { level: 2, strip: strip_image_metadata },
|
||||
advpng: false,
|
||||
pngcrush: false,
|
||||
pngout: false,
|
||||
pngquant: pngquant_options,
|
||||
# JPG
|
||||
jpegoptim: { strip: strip_image_metadata ? "all" : "none" },
|
||||
jpegtran: false,
|
||||
jpegrecompress: false,
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
def self.memoize(*args)
|
||||
(@memoized ||= {})[args] ||= yield
|
||||
end
|
||||
|
||||
def self.supported_images
|
||||
@@supported_images ||= Set.new %w{jpg jpeg png gif svg ico}
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user