From: Joel VanderWerf Date: 2003-09-23T06:14:33+09:00 Subject: Re: Operator overloading Johann Hibschman wrote: > "Robert Klemme" wrote in message news:... > > >>You can't. And you don't need to. As others pointed out already, Ruby >>treats all the assignment arithmetic operators as shortcuts and invokes >>the appropriate operator. So > > > Er. "You don't need to" is rather extreme. What about numerical cases? > > i.e., if m is a large matrix, then "m += 1" and "m = m + 1" are rather > different beasts, since the "obvioius" interpretation of the first involves > simply incrementing the matrix in place, while the second involves a > copy. > > Is there a standard work-around for this? This was one of the reasons I > stuck with python over ruby, but I've got to admit that I didn't spend a > huge amount of time researching. narray has self.add! other self.sbt! other self.mul! other self.div! other self.mod! other which presumably are in-place ops. Anyway, they are faster than *= and friends: user system total real warmup 16.980000 2.850000 19.830000 ( 22.501646) using *= and /= 0.400000 0.050000 0.450000 ( 0.462865) using mul! and div! 0.160000 0.020000 0.180000 ( 0.181544) using no ops 0.000000 0.000000 0.000000 ( 0.006473) (on PIII850). ================================= require 'narray' require 'benchmark' Benchmark.bm(22) do |test| reps = 10_000 m = NMatrix.float(100,100).fill(1) test.report("warmup") do (1..reps).each do |i| m *= i m /= i end end m = NMatrix.float(3,3).fill(1) test.report("using *= and /=") do (1..reps).each do |i| m *= i m /= i end end m = NMatrix.float(3,3).fill(1) test.report("using mul! and div!") do (1..reps).each do |i| m.mul! i m.div! i end end m = NMatrix.float(3,3).fill(1) test.report("using no ops") do (1..reps).each do |i| end end end