Last active
December 20, 2015 21:29
-
-
Save ketzusaka/6198106 to your computer and use it in GitHub Desktop.
Option Checking in Ruby: Hash vs Bitwise Operations This is a simple script that compares how fast it is to build option dictionaries and checking them versus using integers and bitwise flagging
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
| require 'benchmark' | |
| class HashedFlags | |
| def initialize(opts = {}) | |
| @silly_prepend = opts.fetch(:silly_prepend, false) | |
| @uppercase = opts.fetch(:uppercase, false) | |
| end | |
| end | |
| SILLY_PREPEND = 0b00000001 | |
| UPPERCASE = 0b00000010 | |
| class BitFlags | |
| def initialize(flags) | |
| @silly_prepend = (flags & SILLY_PREPEND) > 0 | |
| @uppercase = (flags & UPPERCASE) > 0 | |
| end | |
| end | |
| iterations = 5000000 | |
| Benchmark.bm(50) do |bm| | |
| bm.report('using hashes as option flags') do | |
| iterations.times do |i| | |
| hash_set = case i%4 | |
| when 0 then {} | |
| when 1 then {:silly_prepend => true} | |
| when 2 then {:uppercase => true} | |
| when 3 then {:silly_prepend => true, :uppercase => true} | |
| end | |
| HashedFlags.new(hash_set) | |
| end | |
| end | |
| bm.report('using bitwise flags as option flags') do | |
| iterations.times do |i| | |
| flags = case i%4 | |
| when 0 then 0 | |
| when 1 then SILLY_PREPEND | |
| when 2 then UPPERCASE | |
| when 3 then SILLY_PREPEND | UPPERCASE | |
| end | |
| BitFlags.new(flags) | |
| end | |
| end | |
| end | |
| # My Results: | |
| # user system total real | |
| # using hashes as option flags 12.730000 0.030000 12.760000 ( 12.768373) | |
| # using bitwise flags as option flags 7.080000 0.010000 7.090000 ( 7.092274) | |
| # | |
| # | |
| # Just for fun, I ran a similar test under Xcode with ObjC Objects initalized with dictionaries, | |
| # ObjC Objects initialized with flags, and C structs initialized with flags: | |
| # Time elapsed using ObjC objects and flags: 1.151373 | |
| # Time elapsed using ObjC objects and Dictionaries: 5.105790 | |
| # Time elapsed using c structs with flags: 0.061645 | |
| # UPDATE: Reran the C code again with optimized build settings: | |
| # Time elapsed using ObjC objects and flags: 0.732126 | |
| # Time elapsed using ObjC objects and Dictionaries: 4.424255 | |
| # Time elapsed using c structs with flags: 0.000001 (Not sure if the compiler knew nothing was being used and just removed the loop or if it really went this fast) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment