Skip to content

Instantly share code, notes, and snippets.

@jonmagic
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonmagic/b480e26cefdb1722482a to your computer and use it in GitHub Desktop.
Save jonmagic/b480e26cefdb1722482a to your computer and use it in GitHub Desktop.
I've got two arrays with identical elements in different orders that I need to compare and the order doesn't matter. Should I use sort or array subtraction?
Rehearsal --------------------------------------------
sort 1.140000 0.010000 1.150000 ( 1.166011)
subtract 0.610000 0.030000 0.640000 ( 0.672543)
----------------------------------- total: 1.790000sec
user system total real
sort 1.240000 0.010000 1.250000 ( 1.254706)
subtract 0.620000 0.030000 0.650000 ( 0.672024)
require "benchmark"
sort1 = (1..1_000_000).map { rand }
sort2 = sort1.sort
subtract1 = (1..1_000_000).map { rand }
subtract2 = subtract1.sort
Benchmark.bmbm(7) do |x|
x.report("sort") do
raise "mismatch" unless sort1.sort == sort2
end
x.report("subtract") do
raise "mismatch" if (subtract1 - subtract2).any? && (subtract2 - subtract1).any?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment