Structural subtyping (your new {} in int2x) uses reflection for
invocations. That's your first performance problem. Use a trait like
this:
trait SummingInt{
def sum(x:Int):Int
}
implicit def int2x(i: Int) = new SummingInt{
def sum(x: Int) = i + x
}
And performances will be much better:
266447232 in 324
266447232 in 23
266447232 in 241
266447232 in 13
266447232 in 245
266447232 in 15
266447232 in 239
266447232 in 15
266447232 in 251
266447232 in 17
266447232 in 229
266447232 in 15
266447232 in 235
266447232 in 15
266447232 in 228
266447232 in 15
266447232 in 233
266447232 in 15
266447232 in 222
266447232 in 15
In the end performance is still 10 times worse. Your example stresses
the cost of boxing primitives. It wouldn't be as bad if you would do
the same with objects (relative to the actual calculation done). If
you want to get the best performance you will have to optimize tight
loops anyway, so you would probably refrain from using implicits in
this case.
Johannes
-----------------------------------------------
Johannes Rudolph
http://virtual-void.netOn Tue, Mar 24, 2009 at 5:23 AM, Vladimir Kirichenko
<
vladimir.kirichenko@...> wrote:
> object XT {
>
> implicit def int2x(i: Int) = new {
> def sum(x: Int) = i + x
> }
>
> def sum(i:Int, x:Int) = i + x;
>
> def main(args : Array[String]) = {
>
> //simple
> val iterations = 10000000
> var start = System.currentTimeMillis
>
> var i=0;
> var x=0;
>
> while(i < iterations) {
> x = x sum i sum i;
> i = i + 1;
> }
>
> println(x + " in " + (System.currentTimeMillis - start) );
>
> //fast
> start = System.currentTimeMillis
>
> i=0;
> x=0;
>
> while(i < iterations) {
> x = sum(sum(x, i),i);
> i = i + 1;
> }
>
> println(x + " in " + (System.currentTimeMillis - start) );
>
> }
> }