Created
December 10, 2025 06:24
-
-
Save shugo/c6367f4139bc2d8df9f9199c49cbbcdf to your computer and use it in GitHub Desktop.
Benchmark for String#strip etc.
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" | |
| SPACES = ["\0", *("\t".."\r"), " "].join | |
| TARGET = SPACES + "x" * 1024 + SPACES | |
| Benchmark.bmbm do |x| | |
| x.report("strip()") do | |
| 10000.times do | |
| TARGET.strip | |
| end | |
| end | |
| x.report('lstrip("\0 \t-\r")') do | |
| 10000.times do | |
| TARGET.lstrip("\0 \t-\r") | |
| end | |
| end | |
| x.report('sub(/\A[\0\s]+/, "")') do | |
| 10000.times do | |
| TARGET.sub(/\A[\0\s]+/, "") | |
| end | |
| end | |
| x.report('rstrip("\0 \t-\r")') do | |
| 10000.times do | |
| TARGET.rstrip("\0 \t-\r") | |
| end | |
| end | |
| x.report('sub(/[\0\s]+\z/, "")') do | |
| 10000.times do | |
| TARGET.sub(/[\0\s]+\z/, "") | |
| end | |
| end | |
| x.report('strip("\0 \t-\r")') do | |
| 10000.times do | |
| TARGET.strip("\0 \t-\r") | |
| end | |
| end | |
| x.report('gsub(/\A[\0\s]+|[\0\s]+\z/, "")') do | |
| 10000.times do | |
| TARGET.gsub(/\A[\0\s]+|[\0\s]+\z/, "") | |
| end | |
| end | |
| x.report('sub(/\A[\0\s]+/, "").sub(/[\0\s]+\z/, "")') do | |
| 10000.times do | |
| TARGET.sub(/\A[\0\s]+/, "").sub(/[\0\s]+\z/, "") | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment