Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't tokenize string when counting characters #3873

Merged
merged 1 commit into from Dec 6, 2011

Conversation

iangreenleaf
Copy link
Contributor

The length validation in ActiveModel offers a :tokenizer option, but when none is given it defaults to using // to split the string by character. This adds up to a serious performance hit when validating long strings. AFAICT it's faster, easier, and works just as well to use String#length unless a tokenizer is provided.

A simple wall-time benchmark:

class Foo
  include ActiveModel::Validations
  attr_accessor :bar
  validates_length_of :bar, :maximum => 1
end

LONG_STRING = "a" * 100000

100.times do
  f = Foo.new
  f.bar = LONG_STRING
  f.valid?
end

Before:

real  0m6.196s
user  0m6.113s
sys   0m0.077s

After:

real  0m0.720s
user  0m0.650s
sys   0m0.063s

josevalim added a commit that referenced this pull request Dec 6, 2011
Don't tokenize string when counting characters
@josevalim josevalim merged commit 1ee832b into rails:master Dec 6, 2011
@tolgap
Copy link

tolgap commented Oct 25, 2013

@josevalim What happens if your string contains a new line? Rails receives new lines as \r\n and it reads that as two characters. I just ran against this issue. So my choice was to call gsub!("\r\n", \n) on my attribute in the params hash in my controller to get validates_length_of() to work as expected.

What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants