class Numeric
def sign
self<0?-1:self>0?1:0
end
end
…but it should be much faster if be defined in the original class.
a) Why do you need it to be so fast? Two comparisons seems pretty
lightweight to me!
b) Why do you think it’s generally useful? I think such a method would
have helped me only once or twice in all my programming years.
c) You can implement that more compactly (if not more efficiently) as:
lightweight to me!
You forget function lookup: there is three function lookup for this
code. Hardcoded in C is way faster (with only one function lookup).
b) Why do you think it’s generally useful? I think such a method would
have helped me only once or twice in all my programming years.
There is only one reason: It is a standard function used in mathematics
and
nearly everybody knows a function names “sign” or “sgn” from other
programming
languages.
I think that the code for this method is still there in the kernel.
c) You can implement that more compactly (if not more efficiently) as:
irb(main):001:0> class Numeric; def sign; self <=> 0; end; end
It was only an example to describe what I mean. I have no suggestions
for an
implementation in the Ruby kernel.
I only think, that a mathematical standard function should be available.
a) Why do you need it to be so fast? Two comparisons seems pretty
lightweight to me!
You forget function lookup: there is three function lookup for this
code. Hardcoded in C is way faster (with only one function lookup).
I actually hadn’t forgotten it, but (mistakenly) thought that < and >
didn’t have normal method overhead. So, the spaceship operator is
actually more terse and faster:
class Numeric
def sign1; self < 1 ? -1 : self > 1 ? 1 : 0; end
def sign2; self<=>0; end
def sign3; 0; end
end
So, if we assume that it would be about as fast as #abs, then you’re
talking about saving about 1.3 MICRO seconds per call (on a 3GHz P4). I
would be surprised (and interested) if saving that amount of time made
a difference in someone’s application, for this particular method.
To put it in perspective:
Suppose your Ruby program were controlling a game or simulation.
Suppose you were getting 30fps. Suppose you were calling this method
10,000 times PER FRAME. The difference between having this method
rewritten in the core and using the spaceship operator gets you all the
way to…30.9fps.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.