caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] Obj question
@ 2011-05-10 15:15 David Allsopp
  0 siblings, 0 replies; only message in thread
From: David Allsopp @ 2011-05-10 15:15 UTC (permalink / raw)
  To: OCaml List

I have need of the following type in some code:

	type 'a tbc = Confirmed of 'a | TBC of 'a

When values of this type are used, one usually wants to extract either the
tag or the value (i.e. matching on both is unusual). An alternative would be
to have:

	type 'a tbc = 'a * bool

but the "problem" is that this version requires two blocks for each value
where the first type only requires one block. It turns out that the compiler
automatically optimises this just to retrieve field 0 of the block:

	let get_tbc_value = function Confirmed x -> x | TBC x -> x

so there's no need to resort to Obj there. The same is not true for this:

	let safe_is_tbc = function TBC _ -> true | Confirmed _ -> false

which generates a branch. This is "better":

	external is_tbc : 'a tbc -> bool = "caml_obj_tag"

which takes advantage that the tag values (once converted to OCaml ints by
caml_obj_tag) are the same as the representations for [true] and [false].

So I have two questions:

a) Is that subtle use of caml_obj_tag "safe" (caml_obj_tag, btw, is
otherwise known as Obj.tag) ... bearing in mind the usual caveats that this
is buried well within a module, clearly commented and right next to the type
definition, etc. etc.
b) Is there a way of writing is_tbc without resorting to Obj which doesn't
generate a branch?

I should add that I'm posing this more from curiosity than because I'm
particularly worried about micro-managing performance... I expect my
application spends considerably more time waiting for the database query
actually to return the results than it does processing them using either
representation!


David


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2011-05-10 15:17 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2011-05-10 15:15 [Caml-list] Obj question David Allsopp

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).