Merge: lib/string: `Int::to_s` shortcuts 0 and 1
authorJean Privat <jean@pryen.org>
Wed, 18 Mar 2015 05:41:48 +0000 (12:41 +0700)
committerJean Privat <jean@pryen.org>
Wed, 18 Mar 2015 05:41:48 +0000 (12:41 +0700)
Valgrid said it is used a lot.

So I mixed (`-m`) nitc with the following module

~~~nit
import counter

redef class Int
redef fun to_s
do
sys.itos_cpt.inc(self)
return super
end
end

redef class Sys
var itos_cpt = new Counter[Int]
redef fun run
do
super
itos_cpt.print_summary
itos_cpt.print_elements(10)
end
end
~~~

The result shows that `0` and `1` are the top `to_s`-ized numbers.

~~~
  0: 13554 (9.29%)
  1: 10012 (6.86%)
  2: 5671 (3.88%)
~~~

So I just shortcut-them to reduce allocations.

With nitc/nitc/nitc:
before: 0m6.756s
after: 0m6.632s (-2%)

Pull-Request: #1207
Reviewed-by: Alexis Laferrière <alexis.laf@xymus.net>
Reviewed-by: Alexandre Terrasa <alexandre@moz-code.org>

lib/standard/string.nit

index e78f655..63c8226 100644 (file)
@@ -1953,6 +1953,10 @@ redef class Int
        #     assert 1.to_s            == "1"
        #     assert (-123).to_s       == "-123"
        redef fun to_s do
+               # Fast case for common numbers
+               if self == 0 then return "0"
+               if self == 1 then return "1"
+
                var nslen = int_to_s_len
                var ns = new NativeString(nslen + 1)
                ns[nslen] = '\0'