Skip to content

Commit

Permalink
Prefer Array.new(n) {} to n.times.map {}
Browse files Browse the repository at this point in the history
* It is quite a bit faster:
  ruby -rbenchmark/ips -e 'Benchmark.ips { |x| x.report("times.map") { 1000.times.map {} }; x.report("Array.new") { Array.new(1000) {} }; x.compare! }'
  ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [x86_64-linux]
  Warming up --------------------------------------
         times.map   976.000 i/100ms
         Array.new     1.641k i/100ms
  Calculating -------------------------------------
         times.map      9.808k (± 0.3%) i/s -     49.776k in   5.075013s
         Array.new     16.601k (± 1.0%) i/s -     83.691k in   5.041970s

  Comparison:
         Array.new:    16600.8 i/s
         times.map:     9808.2 i/s - 1.69x  slower
  • Loading branch information
eregon committed Feb 14, 2024
1 parent d00c1bb commit debef8c
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions templates/lib/prism/serialize.rb.erb
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ module Prism
end

def load_line_offsets
source.instance_variable_set :@offsets, load_varuint.times.map { load_varuint }
source.instance_variable_set :@offsets, Array.new(load_varuint) { load_varuint }
end

def load_comments
load_varuint.times.map do
Array.new(load_varuint) do
case load_varuint
when 0 then InlineComment.new(load_location)
when 1 then EmbDocComment.new(load_location)
Expand All @@ -98,10 +98,10 @@ module Prism

def load_metadata
comments = load_comments
magic_comments = load_varuint.times.map { MagicComment.new(load_location, load_location) }
magic_comments = Array.new(load_varuint) { MagicComment.new(load_location, load_location) }
data_loc = load_optional_location
errors = load_varuint.times.map { ParseError.new(load_embedded_string, load_location, load_error_level) }
warnings = load_varuint.times.map { ParseWarning.new(load_embedded_string, load_location, load_warning_level) }
errors = Array.new(load_varuint) { ParseError.new(load_embedded_string, load_location, load_error_level) }
warnings = Array.new(load_varuint) { ParseWarning.new(load_embedded_string, load_location, load_warning_level) }
[comments, magic_comments, data_loc, errors, warnings]
end

Expand Down

0 comments on commit debef8c

Please sign in to comment.