避免不必要计算策略及示例
- 缓存计算结果:
- 策略:对于一些重复计算且结果不随运行时状态频繁变化的函数,将其计算结果缓存起来,避免重复计算。
- 示例:
class MathOperations
def initialize
@factorial_cache = {}
end
def factorial(n)
return @factorial_cache[n] if @factorial_cache.key?(n)
result = 1
(1..n).each do |i|
result *= i
end
@factorial_cache[n] = result
result
end
end
math_ops = MathOperations.new
puts math_ops.factorial(5)
puts math_ops.factorial(5) # 第二次调用直接从缓存取结果,避免重复计算
- 条件判断优化:
- 策略:在响应式代码中,通过合理的条件判断,避免进入不必要的计算逻辑。
- 示例:
def expensive_operation(x)
# 这里模拟一个复杂计算
x * x * x * x
end
def conditional_computation(x)
if x > 10
expensive_operation(x)
else
x
end
end
避免不必要事件触发策略及示例
- 防抖(Debounce):
- 策略:在事件频繁触发的场景下,设置一个延迟时间,在延迟时间内如果事件再次触发,则重置延迟时间,只有在延迟时间结束且没有新的事件触发时,才执行实际的处理逻辑。
- 示例:
require 'timeout'
class Debouncer
def initialize(delay)
@delay = delay
@timer = nil
end
def call(&block)
if @timer
@timer.cancel
end
@timer = Timeout::timeout(@delay) do
block.call
end
end
end
debouncer = Debouncer.new(1) # 延迟1秒
count = 0
5.times do
debouncer.call do
count += 1
puts "Debounced operation executed. Count: #{count}"
end
sleep(0.5)
end
- 节流(Throttle):
- 策略:规定在一定时间间隔内,只能触发一次事件处理逻辑,即使事件触发频率更高,也不会重复执行处理逻辑,而是按固定时间间隔执行。
- 示例:
class Throttler
def initialize(interval)
@interval = interval
@last_call_time = nil
end
def call(&block)
if @last_call_time.nil? || Time.now - @last_call_time >= @interval
block.call
@last_call_time = Time.now
end
end
end
throttler = Throttler.new(2) # 每2秒执行一次
count = 0
10.times do
throttler.call do
count += 1
puts "Throttled operation executed. Count: #{count}"
end
sleep(1)
end