Skip to content

Instantly share code, notes, and snippets.

@jaredmoody
Created May 3, 2017 17:23
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 jaredmoody/d2a1e83de2f91fd6865920cd01a8b497 to your computer and use it in GitHub Desktop.
Save jaredmoody/d2a1e83de2f91fd6865920cd01a8b497 to your computer and use it in GitHub Desktop.
Benchmark for determining if array contains any member of another array
require 'benchmark/ips'
require 'set'
puts "ruby version: #{RUBY_VERSION}"
CHEESES = %w(chedder stilton brie mozzarella feta haloumi).freeze
FOODS = %w(pizza feta foods bread biscuits yoghurt bacon).freeze
Benchmark.ips do |b|
b.report("&, empty?") { (FOODS & CHEESES).empty? }
b.report("any?, include?") { FOODS.any? {|food| CHEESES.include?(food) } }
b.report("Set disjoint") { Set.new(CHEESES).disjoint? Set.new(FOODS) }
b.compare!
end
# My results:
#
# ruby version: 2.2.6
# Warming up --------------------------------------
# &, empty? 42.348k i/100ms
# any?, include? 112.146k i/100ms
# Set disjoint 7.278k i/100ms
# Calculating -------------------------------------
# &, empty? 507.050k (± 6.2%) i/s - 2.541M in 5.032420s
# any?, include? 2.125M (± 5.5%) i/s - 10.654M in 5.030139s
# Set disjoint 81.391k (± 3.7%) i/s - 407.568k in 5.014699s
#
# Comparison:
# any?, include?: 2125373.3 i/s
# &, empty?: 507049.7 i/s - 4.19x slower
# Set disjoint: 81390.6 i/s - 26.11x slower
# *************************************************************
# ruby version: 2.3.4
# Warming up --------------------------------------
# &, empty? 43.809k i/100ms
# any?, include? 135.902k i/100ms
# Set disjoint 8.354k i/100ms
# Calculating -------------------------------------
# &, empty? 553.701k (± 4.2%) i/s - 2.804M in 5.073096s
# any?, include? 2.415M (± 7.0%) i/s - 12.095M in 5.043469s
# Set disjoint 79.318k (±10.2%) i/s - 392.638k in 5.013309s
#
# Comparison:
# any?, include?: 2414705.1 i/s
# &, empty?: 553700.7 i/s - 4.36x slower
# Set disjoint: 79318.2 i/s - 30.44x slower
@davidkovsky
Copy link

davidkovsky commented May 4, 2017

require 'set'

puts "ruby version: #{RUBY_VERSION}"

CHEESES = %w(    abilities
    above
    absolutely
    abstracts
    academic
    academics
    accompanied
    according
    accountability
    accounting
    accredited
    accuracy
    actively
    actors
    adapted
    adapter
    administration
    admissions
    advance
    advantage
    advantages
    adventures
    advertisement
    advertisements
    advice
    advised
    advisor
    aerial
    affects
    affiliates
    aggressive
    agricultural
    ahead
    allow
    alloy
    also
    alter
    aluminum
    amend
    amounts
    analog
    analyses
    andorra
    anime
    announce
    anonymous
    answer
    answers
    anticipated
    apart
    apollo
    apparent
    apple
    appliances
    approval
    approximately
    aquarium
    arbor
    architects
    arnold
    arrange
    arrested
    arrival
    arthur
    artificial
    artists
    ascii
    aspect
    aspects
    assembled
    asset
    assigned
    associates
    assumption
    assurance
    atmosphere
    attraction
    austin
    australian
    automobile
    avatar
    average
    awesome
    backgrounds
    backing
    badge
    bailey
    baker
    banana
    bands
    barbados
    bargain
    bargains
    barnes
    batteries
    beam
    bean
    bear
    beautifully
    bedding
    bedford
    begin
    beginners
    behavior
    belief
    believes
    bell
    benefits
    berlin
    bernard
    beside
    between
    bicycle
    billion
    bingo
    birmingham
    blades
    blocking
    blonde
    bone
    booking
    bookmarks
    boolean
    booth
    boots
    bored
    both
    breakfast
    breaking
    breaks
    bridge
    briefing
    broadcast
    bruce
    builders
    bunch
    busy
    buttons
    cable
    cache
    calcium
    calculator
    california
    camera
    cameras
    campaigns
    canal
    cancellation
    candidates
    capable
    capital
    careers
    carl
    carmen
    carpet
    cars
    cartridge
    case
    casey
    cash
    casino
    casting
    catalog
    catering
    cats
    caught
    causes
    ceiling
    cell
    cellular
    cent
    centered
    ceremony
    chambers
    champagne
    chancellor
    changelog
    channels
    chapter
    charging
    charleston
    charming
    charts
    chase
    cheapest
    choices
    chorus
    circular
    classics
    classifieds
    cleaners
    clearing
    clerk
    clicking
    client
    clinic
    club
    cluster
    coaches
    coast
    cocktail
    coins
    cold
    colleague
    collectables
    collectible
    collection
    collections
    collector
    color
    combination
    combine
    combo
    comfortable
    comic
    commander
    commentary
    commented
    commodity
    companion
    comparable
    competitive
    compiler
    compliance
    composed
    composition
    computational
    concept
    concerns
    concerts
    concluded
    conference
    config
    configured
    confused
    connect
    connection
    consciousness
    considering
    consultancy
    consultant
    contains
    context
    continually
    continued
    continuity
    contracting
    contributed
    contributing
    contributor
    contributors
    controlling
    convergence
    conversation
    convertible
    conviction
    convinced
    cookie
    cookies
    cooling
    cooperative
    coordinate
    copied
    copies
    copper
    copy
    cordless
    cornwall
    corporate
    corporation
    correct
    correctly
    costs
    costumes
    county
    courage
    courses
    covered
    creativity
    creator
    creature
    criteria
    culture
    curriculum
    customers
    cycles
    daniel
    davis
    dawn
    deal
    decide
    declaration
    decorating
    decrease
    deep
    defensive
    deferred
    delays
    delivery
    demographic
    department
    departure
    depth
    describe
    design
    designation
    desktops
    determined
    device
    dialogue
    dice
    dictionaries
    differential
    direct
    directly
    directory
    disclose
    discount
    discuss
    discussions
    disk
    disorder
    displayed
    dist
    distribute
    distributor
    document
    does
    dogs
    dollars
    dosage
    doubt
    download
    dozen
    drama
    dramatic
    drew
    drill
    drilling
    dual
    duncan
    duration
    durham
    dutch
    duties
    dvds
    eagle
    earned
    eastern
    ebook
    edit
    edited
    editing
    editor
    editorial
    effects
    eight
    elections
    electronics
    elegant
    elementary
    elements
    elephant
    elephants
    eleven
    eligible
    emerging
    emphasis
    employment
    enable
    enclosure
    encoding
    encouraging
    ended
    endif
    enforcement
    engaging
    enhanced
    entertainment
    entrepreneur
    envelope
    escape
    escorts
    establish
    established
    euro
    evaluate
    evaluating
    event
    evidence
    example
    except
    exception
    exceptional
    exchanges
    exclusion
    exclusive
    execution
    exemption
    exercise
    exhaust
    exist
    exit
    exotic
    expanded
    expects
    expenses
    exterior
    facilitate
    facility
    facts
    fairly
    fantastic
    farms
    faster
    feature
    featuring
    fewer
    fields
    fifth
    figured
    filters
    finder
    finish
    firms
    fish
    fishing
    fixed
    flags
    fleece
    flight
    florida
    flower
    flux
    flying
    focuses
    focusing
    follow
    foot
    football
    footwear
    fortune
    forward
    founder
    four
    framing
    frequent
    friend
    friends
    functionality
    funding
    further
    gain
    gains
    gaming
    gateway
    generates
    genome
    genre
    geological
    gibraltar
    glass
    globe
    glossary
    gnome
    golden
    gone
    gothic
    gotten
    governing
    government
    grades
    gradually
    greenhouse
    gross
    grow
    grows
    guards
    guided
    guides
    halifax
    handbags
    hansen
    happen
    happening
    happens
    hardcover
    hardly
    harris
    have
    hayes
    healthy
    heard
    heath
    helen
    hence
    herbal
    here
    herein
    herself
    hidden
    highlight
    highlighted
    hill
    hints
    hired
    hist
    hobby
    holding
    homepage
    honor
    hopefully
    house
    household
    houses
    hugh
    hull
    humanity
    humidity
    hydrogen
    hypothetical
    icon
    identification
    illustration
    images
    import
    improve
    improved
    incidence
    incident
    income
    incorrect
    increasingly
    indiana
    individual
    industrial
    informative
    infrastructure
    inns
    inquire
    inquiry
    inserted
    installing
    instead
    institution
    institutions
    instructors
    insured
    integrated
    intelligent
    interact
    interactive
    interesting
    interests
    interference
    into
    introduces
    introducing
    investigations
    investor
    invited
    invoice
    italy
    jacob
    jade
    jaguar
    jamie
    january
    java
    jeremy
    jesse
    jets
    joan
    joel
    johnston
    jokes
    jose
    judy
    julia
    june
    justify
    katie
).freeze

FOODS = %w(    keen
    keith
    kevin
    keywords
    kilometers
    kingdom
    kingston
    kits
    kitten
    kittens
    knee
    knights
    knock
    know
    labor
    laboratory
    lace
    ladder
    laden
    lang
    large
    laser
    latin
    lauren
    lawyer
    league
    lean
    learning
    least
    leaves
    legacy
    length
    lens
    leonard
    liable
    librarian
    lifetime
    liked
    limit
    limiting
    limits
    linda
    line
    lined
    link
    linux
    listing
    literacy
    literary
    live
    liverpool
    lives
    lloyd
    lock
    locked
    logged
    logging
    logistics
    logo
    longer
    lopez
    lost
    loving
    lucky
    lucy
    machines
    mail
    mailing
    mailman
    maine
    maldives
    mandatory
    manga
    manner
    manufactured
    marc
    margaret
    marked
    markets
    mart
    math
    mating
    maximum
    meanwhile
    measuring
    medicines
    members
    membership
    memo
    merchandise
    merchant
    merely
    merge
    metadata
    meters
    metropolitan
    mighty
    milan
    mild
    mile
    millions
    milwaukee
    miniature
    minister
    minor
    mixing
    mobiles
    modification
    modifications
    modules
    molecular
    monetary
    monica
    monitored
    monroe
    montgomery
    moreover
    motion
    motors
    mountains
    movers
    moving
    much
    multimedia
    music
    musical
    musicians
    mutual
    muze
    myrtle
    mysterious
    naples
    natural
    naturals
    necessary
    necklace
    need
    neighbor
    neon
    nerve
    netherlands
    neural
    nevertheless
    newer
    newsletter
    nickel
    night
    node
    notebook
    notebooks
    notification
    notified
    nyancat
    oakland
    objective
    observation
    obtaining
    occasionally
    occupational
    odds
    offer
    officially
    ohio
    okay
    olive
    onion
    onto
    opened
    operate
    opponents
    opposed
    oracle
    ordinance
    organizations
    oscar
    overcome
    overnight
    painted
    paintings
    palace
    palm
    pamela
    paperbacks
    paraguay
    parcel
    parent
    park
    parks
    particles
    parties
    partition
    parts
    passed
    paths
    patrick
    payment
    payroll
    peak
    pearl
    pending
    peninsula
    penny
    people
    percentage
    periodically
    peripherals
    permit
    pete
    petroleum
    phantom
    pharmacology
    phenomenon
    philips
    phoenix
    phone
    phrases
    physically
    pick
    pike
    pine
    pins
    plan
    plane
    plastics
    plate
    platinum
    pleased
    plot
    poland
    polls
    polymer
    polyphonic
    popularity
    portions
    positive
    possibilities
    possible
    postcard
    posts
    powell
    practice
    precious
    prefix
    premier
    prep
    presents
    prevent
    prices
    prince
    principles
    printable
    printers
    prints
    procedure
    proceeding
    proceeds
    process
    processed
    producers
    produces
    products
    professional
    project
    projector
    promotes
    properties
    proposals
    propose
    proposed
    protocols
    proud
    prove
    provided
    provider
    providers
    provision
    publisher
    pull
    pump
    purchased
    pure
    pursuit
    puzzle
    quad
    qualifications
    qualified
    quantity
    question
    queue
    railway
    rainbow
    raising
    range
    ranging
    rank
    rapidly
    rates
    ratings
    rational
    reactions
    reader
    real
    reasoning
    received
    receiver
    receivers
    receives
    receiving
    recent
    recognised
    recommends
    recovered
    recreation
    recruitment
    recycling
    reduce
    reductions
    reference
    referenced
    references
    refinance
    reflect
    refuse
    reggae
    regions
    regularly
    relation
    relaxation
    release
    released
    relief
    relocation
    remain
    remarks
    remembered
    remix
    renewable
    renewal
    replies
    representative
    representatives
    reprints
    request
    require
    required
    requires
    research
    researcher
    reserves
    resolutions
    resolved
    response
    results
    retained
    retro
    return
    review
    reviewer
    ribbon
    river
    rivers
    road
    rocket
    roger
    rogers
    role
    roll
    rolled
    roman
    route
    royal
    runtime
    sacramento
    safely
    sage
    saints
    salmon
    samba
    saved
    saving
    scan
    scanning
    scared
    schedules
    schema
    scope
    scout
    sculpture
    seafood
    seal
    seating
    seconds
    secret
    secretary
    securely
    seeds
    seeing
    selling
    semi
    sentences
    september
    sequence
    serial
    seriously
    servers
    settled
    setup
    shade
    shannon
    shareholders
    shaw
    sheets
    shell
    shepherd
    ship
    shopper
    showtimes
    significance
    signing
    signup
    silent
    silk
    silly
    simple
    simulation
    sing
    sister
    site
    situation
    size
    skilled
    slideshow
    smilies
    smith
    snap
    soap
    socket
    sole
    soma
    some
    songs
    sony
    soon
    sorted
    sources
    spain
    spas
    speaks
    spears
    special
    spectrum
    speech
    speeches
    spell
    spend
    sphere
    sports
    sprint
    started
    statement
    statistical
    stats
    statutory
    stay
    stem
    step
    sterling
    stickers
    stock
    stomach
    stood
    stopped
    stories
    strand
    strategies
    streaming
    strings
    structured
    structures
    students
    studied
    studio
    stuff
    styles
    submitting
    subscriber
    substantial
    suffer
    sufficient
    sugar
    suggestion
    suggests
    suitable
    sullivan
    sunglasses
    sunset
    sunshine
    superintendent
    supervisor
    suppose
    surname
    surround
    survey
    survivors
    susan
    swedish
    sweet
    swim
    switching
    sydney
    sympathy
    symphony
    systematic
    tablet
    tabs
    tackle
    taken
    taking
    talent
    talked
    tamil
    tapes
    target
    targets
    taylor
    teams
    technician
    technique
    techniques
    telescope
    temporary
    tenant
    tender
    tension
    terrace
    tested
    thanks
    theory
    therapeutic
    thermal
    think
    thinks
    thompson
    thomson
    thorough
    though
    thousand
    thread
    threaded
    threats
    through
    throw
    thursday
    tier
    title
    titles
    tone
    tool
    tooth
    touring
    towards
    town
    towns
    trade
    trainers
    transaction
    transferred
    transit
    transition
    transmit
    transmitted
    transparency
    trash
    travels
    treasury
    treat
    tribune
    trio
    trip
    triple
    troops
    troubleshooting
    true
    trustees
    trying
    tsunami
    tubes
    tucson
    turn
    twins
    type
    ultimate
    under
    understand
    understanding
    uniform
    university
    upgrade
    upper
    urls
    uses
    utilities
    vacancies
    vaccine
    valley
    value
    valve
    vanilla
    variable
    variations
    varies
    ventures
    venue
    very
    victorian
    view
    viewer
    vincent
    vinyl
    virtue
    visitor
    vital
    vocational
    volunteer
    vote
    voters
    votes
    waiting
    wales
    walking
    wallpapers
    walt
    ware
    warehouse
    warner
    warrior
    wash
    waterproof
    wear
    weblogs
    website
    webster
    wednesday
    weekends
    weighted
    weights
    welcome
    west
    westminster
    whale
    widely
    wider
    wifi
    will
    willing
    wireless
    worcester
    working
    worldcat
    writing
    wrote
    yale
    yearly
    yeast
    yellow
    zebra
    zinc
    zone
    zones
    zoom).freeze

Benchmark.ips do |b|
  b.report("&, empty?") { (FOODS & CHEESES).empty? }
  b.report("any?, include?") { FOODS.any? {|food| CHEESES.include?(food) } }
  b.report("Set disjoint") { Set.new(CHEESES).disjoint? Set.new(FOODS) }
  b.compare!
end```

Ruby 2.4.1 gave me:
Warming up --------------------------------------
           &, empty?
     1.640k i/100ms
      any?, include?   122.000  i/100ms
        Set disjoint   390.000  i/100ms
Calculating -------------------------------------
           &, empty?     16.919k (± 2.6%) i/s -     85.280k in   5.044059s
      any?, include?      1.213k (± 3.3%) i/s -      6.100k in   5.035891s
        Set disjoint      3.983k (± 4.1%) i/s -     20.280k in   5.100635s

Comparison:
           &, empty?:    16918.6 i/s
        Set disjoint:     3983.1 i/s - 4.25x  slower
      any?, include?:     1212.7 i/s - 13.95x  slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment