Skip to content

chore: improve get_value's performance#298

Open
nvh0412 wants to merge 1 commit intolaserlemon:mainfrom
nvh0412:chore/improve_get_value_perf
Open

chore: improve get_value's performance#298
nvh0412 wants to merge 1 commit intolaserlemon:mainfrom
nvh0412:chore/improve_get_value_perf

Conversation

@nvh0412
Copy link
Copy Markdown

@nvh0412 nvh0412 commented Oct 5, 2025

Reducing object allocations and also improve time complexity of get_value

  1. There is 1 object allocation each time we look up the key
  2. O(1) lookup after initial build

The previous code would loop through all key value every time in ENV. The pre-built hash is over 2,500x faster than the alternatives.

Benchmark

require 'benchmark'

# Setup
ENV.clear
1000.times { |i| ENV["KEY_#{i}"] = "value_#{i}" }
ENV["TARGET_KEY"] = "target_value"
key = "TARGET_KEY"

# Method 1: Pre-built hash
env_lowercase = ENV.each_with_object({}) { |(k, v), h| h[k.downcase] = v }

# Method 2: Direct iteration
def find_case_insensitive(hash, key)
  key_down = key.downcase
  hash.each do |k, v|
    return v if k.downcase == key_down
  end
  nil
end

Benchmark.bm do |x|
  x.report("Pre-built hash:") do
    10000.times { env_lowercase[key.downcase] }
  end
  
  x.report("Direct iteration:") do
    10000.times { find_case_insensitive(ENV, key) }
  end
  
  x.report("Current detect:") do
    10000.times { ENV.detect { |k, _| k.downcase == key.downcase }&.last }
  end
end

Result:

Screenshot 2025-10-05 at 2 19 08 PM

@nvh0412
Copy link
Copy Markdown
Author

nvh0412 commented Oct 6, 2025

Hi @laserlemon, I’m open to optimizing has_key?(key) by using a shared case-insensitive key hash if you think it’s worth it. In my project, the get_value(key) method is the hot path, so optimizing that alone is sufficient for me.

Reducing object allocations and also improve time complexity of get_value

1. There is 1 object allocation each time we look up the key
2. O(1) lookup after initial build

The previous code would loop through all key value every time in ENV. The pre-built hash is over 2,500x faster than the alternatives.
@nvh0412 nvh0412 force-pushed the chore/improve_get_value_perf branch from 7284c0d to 7a5471e Compare October 6, 2025 11:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant