rails/rails — pull request #9958 by SamSaffron (2013-03-27 22:44:17+00:00)
Title: Optimise performance of String#blank?

```ruby
require "rubygems"
require "benchmark"

n = 100000

class String
def blank?
self !~ /[^[:space:]]/
end

def blank2?
self =~ /^[[:space:]*]$/m?true:false
end

end

tests = {
:s1 => "",
:s2 => " \r \n",
:s3 => "hello",
:s4 => " hello"
}

Benchmark.bmbm {|x|
tests.each do |k,v|
x.report("blank #{k}") {n.times { v.blank? } }
x.report("blank2 #{k}") {n.times { v.blank2? } }
end
}

```

```
user system total real
blank s1 0.040000 0.000000 0.040000 ( 0.042660)
blank2 s1 0.020000 0.000000 0.020000 ( 0.030270)
blank s2 0.060000 0.000000 0.060000 ( 0.055076)
blank2 s2 0.050000 0.000000 0.050000 ( 0.047653)
blank s3 0.080000 0.000000 0.080000 ( 0.079468)
blank2 s3 0.040000 0.000000 0.040000 ( 0.040230)
blank s4 0.090000 0.000000 0.090000 ( 0.085941)
blank2 s4 0.040000 0.000000 0.040000 ( 0.043885)
```

---

Similar results on both 1.9.3 and 2.0.0

---

Picked this up while looking at a flame graph on Discourse"

![image](https://f.cloud.github.com/assets/5213/311068/b4ae87ec-972f-11e2-809e-c0ea616e98e7.png)

See: http://samsaffron.com/archive/2013/03/19/flame-graphs-in-ruby-miniprofiler about flame graphs

---

Also, I wonder if value_to_boolean in AR should even be calling blank?, shouldn't .nil? || .empty? do ... it would be much faster