慢斯卡拉断言 [英] Slow Scala assert
问题描述
我们最近一直在分析代码,并且遇到了一些令人讨厌的热点.它们的格式为
We've been profiling our code recently and we've come across a few annoying hotspots. They're in the form
assert(a == b, a + " is not equal to " + b)
因为其中一些断言可以在代码中调用,所以字符串concat开始累加的次数很多. assert
定义为:
Because some of these asserts can be in code called a huge amount of times the string concat starts to add up. assert
is defined as:
def assert(assumption : Boolean, message : Any) = ....
为什么不定义为:
def assert(assumption : Boolean, message : => Any) = ....
这样,它就会懒惰地求值.鉴于尚未定义该方法,是否存在一种内联方法来调用带有惰性评估的消息参数的assert?
That way it would evaluate lazily. Given that it's not defined that way is there an inline way of calling assert with a message param that is evaluated lazily?
谢谢
推荐答案
惰性求值对于创建的函数对象也有一些开销.如果您的消息对象已经完全构造(静态消息),则此开销是不必要的.
Lazy evaluation has also some overhead for the function object created. If your message object is already fully constructed (a static message) this overhead is unnecessary.
适合您的用例的方法是sprintf样式:
The appropriate method for your use case would be sprintf-style:
assert(a == b, "%s is not equal to %s", a, b)
只要有特殊功能
assert(Boolean, String, Any, Any)
此实现没有开销,也没有var args数组的开销
this implementation has no overhead or the cost of the var args array
assert(Boolean, String, Any*)
一般情况.
实施toString会被延迟评估,但不可读:
Implementing toString would be evaluated lazily, but is not readable:
assert(a == b, new { override def toString = a + " is not equal to " + b })
这篇关于慢斯卡拉断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!