Are the Date, Time, and DateTime classes necessary?

前端 未结 5 1627
生来不讨喜
生来不讨喜 2020-12-08 00:51

What is the purpose of having Date and Time classes when there is a DateTime class that can handle both?

5条回答
  •  半阙折子戏
    2020-12-08 01:08

    I know there is an accepted answer but I have something to add. The Date class is a heavyweight, academic strength class. It can handle all sorts of RFC's, parse the strangest things and converts julian dates from thousand years ago to gregorian with the reform date of choice. The Time class is lightweight and it does not know of any of this stuff. It's cheaper and that shows up in a benchmark:

    require 'benchmark'
    require 'date'
    
    Benchmark.bm(10) do |x|
      x.report('date'){100000.times{Date.today} }
      x.report('datetime'){100000.times{DateTime.now} }
      x.report('time'){100000.times{Time.now} }
    end
    

    Result:

                    user     system      total        real
    date        1.250000   0.270000   1.520000 (  1.799531)
    datetime    6.660000   0.360000   7.020000 (  7.690016)
    time        0.140000   0.030000   0.170000 (  0.200738)
    

    (Ruby 1.9.2)

提交回复
热议问题