Kurt Stephens | 16 May 20:45

Re: Singleton methods on Float and Bignum


> We don't do this for strings either, so why should it be something
> special about Fixnums, Bignums or Floats?
> 
> - Matthias
> 

Because they are value classes and value objects should be immutable in
value and behavior.

Preserving the immutability of objects used as values has implications
for memoizing computations.

Examples:

Ruby Strings are not immutable and it causes significant memory issues,
made worse by the fact that each lexical String "constant" allocates a
new String object.  Immediates like Fixnums are not allocated thus
object identity is preserved and operations on Fixnums can be memoized
using object identity as a cache key.

Why doesn't Symbol#to_s return a memoized frozen String?  A Symbol's
name cannot be changed by definition, yet Symbol#to_s returns a new
String each time even if the caller never intends to mutate it.

Mutability of the result of to_s an String "constants" is a programmer
convenience, but it has significant performance implications: consider
that String "" interpolation uses to_s to coerce to String values that
it never mutates.

Suppose that String to Bignum coercion was cached, commonly used Bignums
would likely have the same object identity.  Using object identity could
make Bignum#* memoizable with little effort.  Allowing singleton methods
on Bignums, could render computations with Bignums impossible to memoize.

I have written a in-memory memoizer for methods on Bignum, Rational and
other core value types that increases performance in most cases.

Kurt Stephens
http://kurtstephens.com


Gmane