Reputation: 26660
Is there some difference between Time.now
and Time.new
(without parameters)? May be difference in memory management or some small details?
Upvotes: 3
Views: 2130
Reputation: 665
Using Ruby 2.4.1 and Rails 5.0.3 When using travel_to in tests Time.new does not get affected by it but Time.now does change because of it
Upvotes: 1
Reputation: 16012
now
is an alias for new
. There's no difference between them. Jeff price's get to answer(and his answer is also correct, please up vote his answer if you like this) first, because I was writing and running this benchmark:
Ruby 2.1.2(MRI):
Rehearsal ----------------------------------------------------------------------------
Time.new 0.670000 0.000000 0.670000 ( 0.679709)
Time.now 0.880000 0.010000 0.890000 ( 0.881899)
------------------------------------------------------------------- total: 1.560000sec
user system total real
Time.new 0.720000 0.000000 0.720000 ( 0.719453)
Time.now 0.740000 0.010000 0.750000 ( 0.742711)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.810000 0.000000 0.810000 ( 0.811874)
Time.now 0.830000 0.000000 0.830000 ( 0.831346)
------------------------------------------------------------------- total: 1.640000sec
user system total real
Time.new 0.790000 0.010000 0.800000 ( 0.800082)
Time.now 0.740000 0.000000 0.740000 ( 0.749995)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.680000 0.010000 0.690000 ( 0.690337)
Time.now 0.850000 0.000000 0.850000 ( 0.856800)
------------------------------------------------------------------- total: 1.540000sec
user system total real
Time.new 0.790000 0.010000 0.800000 ( 0.792666)
Time.now 0.770000 0.000000 0.770000 ( 0.777414)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.590000 0.010000 0.600000 ( 0.594650)
Time.now 0.710000 0.010000 0.720000 ( 0.717067)
------------------------------------------------------------------- total: 1.320000sec
user system total real
Time.new 0.870000 0.000000 0.870000 ( 0.872646)
Time.now 0.680000 0.010000 0.690000 ( 0.687092)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.780000 0.010000 0.790000 ( 0.786419)
Time.now 0.780000 0.000000 0.780000 ( 0.789049)
------------------------------------------------------------------- total: 1.570000sec
user system total real
Time.new 0.760000 0.010000 0.770000 ( 0.768194)
Time.now 0.790000 0.010000 0.800000 ( 0.790981)
Run benchmark yourself:
n = 1000000
5.times do
Benchmark.bmbm(40) do |x|
x.report("Time.new"){ n.times { Time.new } }
x.report("Time.now"){ n.times { Time.now } }
end
end
Upvotes: 7
Reputation: 3229
There is no difference.
Time.now is an alias for ::new. Returns a Time object initialized to the current system time.
http://www.ruby-doc.org/core-2.1.4/Time.html#method-c-now
Upvotes: 12