Last active
June 17, 2022 01:10
-
-
Save texpert/3122416b2de1b76da7b9260dceb3f475 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Install the necessary gems: | |
# gem install benchmark-ips | |
# gem install kalibera | |
require 'benchmark/ips' | |
ARRAY = (1..100).to_a.map { |e| [e, e] } | |
def slow_flatten_1 | |
ARRAY.flatten(1) | |
end | |
def slow_flatten | |
ARRAY.flatten | |
end | |
def fast | |
ARRAY.flat_map { |e| e } | |
end | |
Benchmark.ips do |x| | |
x.report('Array.flatten(1)') { slow_flatten_1 } | |
x.report('Array.flatten') { slow_flatten } | |
x.report('Array#flat_map') { fast } | |
x.compare! | |
end | |
# Results | |
Warming up -------------------------------------- | |
Array#map.flatten(1) 9.228k i/100ms | |
Array#map.flatten 4.509k i/100ms | |
Array#flat_map 8.919k i/100ms | |
Calculating ------------------------------------- | |
Array#map.flatten(1) 98.568k (± 5.5%) i/s - 498.312k in 5.071347s | |
Array#map.flatten 47.331k (± 4.1%) i/s - 238.977k in 5.057899s | |
Array#flat_map 93.619k (± 4.4%) i/s - 472.707k in 5.059067s | |
Comparison: | |
Array#map.flatten(1): 98568.4 i/s | |
Array#flat_map: 93619.1 i/s - same-ish: difference falls within error | |
Array#map.flatten: 47330.9 i/s - 2.08x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment