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

[每日见闻-2017-07-27]Rails细节的性能对比 #5

Closed
xiaohesong opened this issue Jul 27, 2017 · 3 comments
Closed

[每日见闻-2017-07-27]Rails细节的性能对比 #5

xiaohesong opened this issue Jul 27, 2017 · 3 comments
Labels

Comments

@xiaohesong
Copy link
Owner

xiaohesong commented Jul 27, 2017

  • method argument
def hello(foo: nil, bar: nil)
end
10_000.times { hello(foo: 1, bar: 2) }

# Runtime => 10.354 ms
def hello(options = {})
  foo, bar = options[:foo], options[:bar]
end
10_000.times { hello(foo: 1, bar: 2) }
# Runtime => 5.064 ms
  • obj.method VS obj attr_reader
class Foo
  def initialize(val)
    @val = val
  end

  def val
    @val
  end
end

object = Foo.new("bar")
100_000.times { object.val }
# Runtime => 9.284 ms
class Foo
  def initialize(val)
    @val = val
  end

  attr_reader :val
end

object = Foo.new("bar")
100_000.times { object.val }
# Runtime => 6.966 ms
@xiaohesong
Copy link
Owner Author

xiaohesong commented Jul 27, 2017

  • Array rand
(1..100_000).to_a.shuffle!
# Runtime => 6.968 ms
(1..100_000).to_a.sort_by { rand }
# Runtime => 94.396 ms
  • each VS while
100_000.times do |n|
  # Do something
end
# Runtime: 4.395 ms
n = 0

while n < 100_000
  # Do something
  n += 1
end
# Runtime: 1.878 ms

@xiaohesong
Copy link
Owner Author

  • Block
def hello(&block)
  block.call
end

100_000.times do
  hello { "world" }
end
# Runtime: 72.739 ms
def hello
  yield
end

100_000.times do
  hello { "world" }
end
# Runtime: 18.987 ms

@xiaohesong
Copy link
Owner Author

xiaohesong commented Jul 27, 2017

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

No branches or pull requests

1 participant