ruby-on-rails - 使用安全导航算子后增加时间
问题描述
我有一个名为event
. 其中一个属性是updated_at
which 是date time
. 我想增加 15 秒来updated_at
处理我正在做的一些测试。
当我这样做时它会起作用event.updated_at + 15.seconds
测试时,有时event
是nil
. 所以我使用安全导航器处理它&.
但是,我现在无法添加秒数,因为我无法在安全导航器运算符之后链接普通方法调用。
所以这行不通event&.updated_at + 15.seconds
有谁知道使用安全导航器后如何增加时间?
我想我能做到
if event
event.updated_at + 15.seconds
end
但一直在寻找更好的方法
解决方案
您可以根据自己的喜好使用几种不同的方法。但是让我们对它们进行基准测试!
n = 10_000_000
Benchmark.bm do |test|
test.report('if:') { n.times { nil.updated_at + 15.seconds if nil } }
test.report('unless:') { n.times { nil.updated_at + 15.seconds unless nil.nil? } }
test.report('& + send:') { n.times { nil&.updated_at&.send(:+, 15.seconds) } }
test.report('& + try:') { n.times { nil&.updated_at.try(:+, 15.seconds) } }
end
# user system total real
# if: 0.390000 0.000000 0.390000 (0.392020)
# unless: 0.570000 0.000000 0.570000 (0.569032)
# & + send: 0.380000 0.000000 0.380000 (0.381654)
# & + try: 13.950000 0.000000 13.950000 (13.959887)
结果以秒为单位。所以选择最快或最有吸引力的:)
推荐阅读
- azure - Web 应用程序未验证自定义域名
- android - 颤振路线。移动应用程序开发
- spring-boot - Spring Data MongoRepository 保存导致重复键错误
- angularjs - 我如何在angularjs中从aws s3压缩和下载完整文件夹
- javascript - 如何一键切换音频播放/暂停
- java - [无法将类型“java.lang.String”的属性值转换为所需类型“java.sql.Time”
- python - Pandas-Python 日期范围
- java - Java 文件的行为很奇怪
- objective-c - xcode 9:presentViewController 删除所有以前的控制器
- c# - 动态更改 xml 文件中的元素名称