[m-rev.] for review: faster int to decimal string conversion

Julien Fischer jfischer at opturion.com
Sun Oct 17 16:44:42 AEDT 2021


For review by anyone:

A few things:

1. Speeding up all the int to decimal string conversion operations even
more is possible. I will look at doing this in subsequent diffs.

2. It should also be possible to make int_to_base_string faster than
it currently is.

3. Should I add the benchmarking code I used to the benchmarks?

--------------------------------------

Faster int to decimal string conversion.

The int_to_string conversion operation is currently implemented using
int_to_base_string/3. For the other integer types, we implement the equivalent
conversion using library code in the target languages. Benchmarking
int_to_string shows that it is *much* slower than the equivalent target
language code. When converting 10,000,000 randomly generated (64-bit) integers,
the timings in asm_fast.gc are:

     int_to_base_string: 37100 ms
        target language: 8920 ms

(Repeated six times using benchmark_det_io/7).

library/string.m:
     Implement int_to_string using foreign code.

Julien.

diff --git a/library/string.m b/library/string.m
index 521bca4..edee14b 100644
--- a/library/string.m
+++ b/library/string.m
@@ -5589,14 +5589,37 @@ from_char(Char) = char_to_string(Char).

  %---------------------%

-int_to_string(N) = S1 :-
-    int_to_string(N, S1).
+:- pragma foreign_proc("C",
+    int_to_string(I::in) = (S::uo),
+    [will_not_call_mercury, promise_pure, thread_safe, will_not_modify_trail],
+"
+    char buffer[21]; // 1 for sign, 19 for digits, 1 for nul.
+    sprintf(buffer, ""%"" MR_INTEGER_LENGTH_MODIFIER ""d"", I);
+    MR_allocate_aligned_string_msg(S, strlen(buffer), MR_ALLOC_ID);
+    strcpy(S, buffer);
+").
+
+:- pragma foreign_proc("C#",
+    int_to_string(I::in) = (S::uo),
+    [will_not_call_mercury, promise_pure, thread_safe],
+"
+    S = I.ToString();
+").
+
+:- pragma foreign_proc("Java",
+    int_to_string(I::in) = (S::uo),
+    [will_not_call_mercury, promise_pure, thread_safe],
+"
+    S = java.lang.Integer.toString(I);
+").

  int_to_string(N, Str) :-
-    int_to_base_string(N, 10, Str).
+    Str = int_to_string(N).

  from_int(N) = int_to_string(N).

+%---------------------%
+
  int_to_base_string(N1, N2) = S2 :-
      int_to_base_string(N1, N2, S2).



More information about the reviews mailing list