Add String#start_with? vs String#[].==#112
Add String#start_with? vs String#[].==#112jonathanhefner wants to merge 1 commit intofastruby:masterfrom
Conversation
|
Based on the conversations in #96, I tried a different approach to these benchmarks: require 'benchmark/ips'
PREFIX = '_'
STRINGS = (0..99).map{|n| "#{PREFIX if n.odd?}#{n}" }
FAST = STRINGS.each_index.map do |i|
"STRINGS[#{i}].start_with?(PREFIX)"
end.join(';')
SLOW_LENGTH = STRINGS.each_index.map do |i|
# use `eql?` instead of `==` to prevent warnings
"STRINGS[#{i}][0, PREFIX.length].eql?(PREFIX)"
end.join(';')
SLOW_RANGE = STRINGS.each_index.map do |i|
# use `eql?` instead of `==` to prevent warnings
"STRINGS[#{i}][0...PREFIX.length].eql?(PREFIX)"
end.join(';')
Benchmark.ips do |x|
x.report('String#start_with?', FAST)
x.report('String#[0, n] ==', SLOW_LENGTH)
x.report('String#[0...n] ==', SLOW_RANGE)
x.compare!
endThe code is less clear, but the results show a sharper contrast: If desired, I can update this PR using the above code. Thoughts? |
|
While I guess it's a question of what exactly you're trying to benchmark, note that in the The code as written is probably representative of what most people would do in the real world. But if your focus is on measuring the cost of the various prefix checks themselves, it'd probably be worthwhile to calculate the values once outside the loop and then substitute them in. |
I'm glad you see it as such--that's exactly what I intended. :) Specifically, I've seen this pattern a few times: if template_name.first == "_"
# handle partial view template
endThis uses Active Support's |
4b696f4 to
57890c3
Compare
|
@nirvdrum Thank you for the review! @nirvdrum @jonathanhefner May I add you as collaborators to this repository? |
|
@JuanitoFatas Sure thing! Thanks very much! 😃 🎉 |
|
@JuanitoFatas That'd be fantastic. Thanks! |
Compares e.g.
url.start_with?("http")vsurl[0...4] == "http"A lot of the existing string benchmarks list their "slow" case first, but the contributing guidelines said to list the "fast" case first. If I need to change anything, I would be happy to. Thanks!