1
0

Start using an object pool for shipments

This commit is contained in:
Tim Kächele 2024-12-12 10:54:04 +01:00
parent e91e12c7ea
commit 8945efaf10
4 changed files with 47 additions and 16 deletions

View File

@ -2,6 +2,8 @@
require_relative "planet_express_express/version"
require_relative "planet_express_express/constants"
require_relative "planet_express_express/shipment"
require_relative "planet_express_express/shipment_pool"
require_relative "planet_express_express/shipment_reader"
require_relative "planet_express_express/rules"
require_relative "planet_express_express/discount_budget"

View File

@ -0,0 +1,10 @@
module PlanetExpressExpress
Shipment = Struct.new(
:date,
:size,
:provider,
:price,
:discount,
keyword_init: true
)
end

View File

@ -0,0 +1,24 @@
module PlanetExpressExpress
# A very simple implementation of an object pool for
# shipments.
#
# Using it you can reduce the memory allocations
class ShipmentPool
def initialize(size: 100)
@entries = []
size.times do
@entries.push(Shipment.new())
end
end
def get()
entry = @entries.pop
return entry if entry
Shipment.new
end
def put_back(shipment_entries)
@entries.push(*shipment_entries)
end
end
end

View File

@ -1,15 +1,8 @@
module PlanetExpressExpress
require "date"
class ShipmentReader
Shipment = Struct.new(
:date,
:size,
:provider,
:price,
:discount,
keyword_init: true
)
def initialize(prices)
def initialize(prices, shipment_pool: ShipmentPool.new(size: 10))
@shipment_pool = shipment_pool
@prices = prices
@id = 0
end
@ -31,6 +24,8 @@ module PlanetExpressExpress
if shipment.date.year != current_year || shipment.date.month != current_month
yield shipments
@shipment_pool.put_back(shipments[:all])
shipments.each do |_,v|
v.clear
end
@ -52,13 +47,13 @@ module PlanetExpressExpress
def parse(line)
parts = line.split(" ")
shipment = Shipment.new(
date: Date.strptime(parts[0], "%Y-%m-%d"),
size: parts[1]&.to_sym,
provider: parts[2]&.to_sym,
price: 0,
discount: 0
)
shipment = @shipment_pool.get
shipment.date = Date.strptime(parts[0], "%Y-%m-%d")
shipment.size = parts[1]&.to_sym
shipment.provider = parts[2]&.to_sym
shipment.price = 0
shipment.discount = 0
shipment.price = prices[
[