Skip to content

Instantly share code, notes, and snippets.

@burke
Created August 14, 2009 07:11
Show Gist options
  • Save burke/167684 to your computer and use it in GitHub Desktop.
Save burke/167684 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# Proposed solution to ruby 1.9's multibyte chars.
# -- just let ruby handle it, at least initially.
# -- not many that we're calling ActiveSupport methods
# -- on will have non-ascii characters anyway.
# useless performance metrics (on my macbook)
# ====================================+=======
# String#ascii_only? | 0.22µs
# String#force_encoding("ASCII-8BIT") | 0.60µs
# String#encoding==ASCII_ENCODING | 0.26µs
# If we can safely do Encoding.default_external = Encoding.find("ASCII-8BIT"),
# then this only has 0.2µs overhead in string functions.
if '1.9'.respond_to?(:force_encoding)
ASCII_ENCODING = Encoding.find("ASCII-8BIT")
def do_something(str)
if str.encoding == ASCII_ENCODING
::ActiveSupport::FFI.whatever_function(str)
else
do_the_existing_ruby_stuff()
end
end
else
def do_something(str)
::ActiveSupport::FFI.whatever_function(str)
end
end
# If we can't touch the default encoding, and know it isn't ASCII,
# then this will work, but it has about four times as much overhead, at 0.8µs.
if '1.9'.respond_to?(:force_encoding)
def do_something(str)
if str.ascii_only?
::ActiveSupport::FFI.whatever_function(str.force_encoding("ASCII-8BIT"))
else
do_the_existing_ruby_stuff()
end
end
else
def do_something(str)
::ActiveSupport::FFI.whatever_function(str)
end
end
# If we can't touch the encoding, but aren't sure what it is, then we can combine
# the two approaches above.
if '1.9'.respond_to?(:force_encoding)
ASCII_ENCODING = Encoding.find("ASCII-8BIT")
if Encoding.default_external == ASCII_ENCODING
def do_something(str)
if str.encoding == ASCII_ENCODING
::ActiveSupport::FFI.whatever_function(str)
else
do_the_existing_ruby_stuff()
end
end
else
def do_something(str)
if str.ascii_only?
::ActiveSupport::FFI.whatever_function(str.force_encoding("ASCII-8BIT"))
else
do_the_existing_ruby_stuff()
end
end
end
else
def do_something(str)
::ActiveSupport::FFI.whatever_function(str)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment