4

There is no realloc in OCaml memory.h or alloc.h (byterun/caml). Does that mean that is not possible to realloc an OCaml GC block (or value)? The use-case I'm thinking of is string concat, where the following can be optimized using realloc:

a = a ^ b

In my benchmarks, string concat is actually faster in PHP (5.5) than native-compiled OCaml (4.02.1).

Edit: In another benchmark, Buffer is much faster than PHP concat, and still faster than OCaml concat even when converting the buffer to string in every loop iteration. Code.

Olle Härstedt
  • 3,799
  • 1
  • 24
  • 57
  • 1
    This does not answer your specific question, but if you're doing a lot of string concatenations, it is usually advised to use the `Buffer` module from the standard library. – Virgile Sep 17 '15 at 13:11
  • @Virgile Hi! Yes, it's much faster I discovered. – Olle Härstedt Sep 17 '15 at 16:17

1 Answers1

3

It's true, there's no realloc()-style primitive for OCaml memory.

The efficiency of realloc() isn't a given; it depends on the pattern of calls. Generally speaking it only saves time if there is free space after the reallocated object.

In OCaml this is very unlikely; in the younger GC generation no objects have free space following them; blocks are allocated in decreasing memory order. In the older generation, you can have the odd hole here and there. If compaction has been done recently, only the one old object at the end can have free space after it.

For these reasons, I suspect that realloc() would have almost no benefit in the OCaml GC environment.

I would actually tend to doubt that realloc() is the reason you're getting faster times for PHP than for OCaml. I don't think it's a real timesaver except in unusual circumstances. But maybe you have some measurements that support this theory.

Update

You might want to experiment with the OCaml Buffer module, which will let you concatenate strings imperatively. A buffer is likely to be faster than using the ^ operator for many cases (but has the usual disadvantages of a mutable value).

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • Hey, thanks for the answer. I will analyse the PHP opcodes to see what's happening, will get back. – Olle Härstedt Sep 16 '15 at 22:51
  • (Also you might want to try the OCaml `Buffer` module; see update.) – Jeffrey Scofield Sep 17 '15 at 14:54
  • Thanks, I tested and it is much faster indeed. To what disadvantages are you referring? On compiler level or conceptual level? – Olle Härstedt Sep 17 '15 at 16:17
  • 1
    In my experience there are substantial practical and conceptual benefits when you work with immutable values. There are also advantages for compilation and concurrency. It's a big topic. Here's a famous essay about some of it by John Hughes: [Why Functional Programming Matters](https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf). – Jeffrey Scofield Sep 17 '15 at 17:54