From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from mail3-relais-sop.national.inria.fr (mail3-relais-sop.national.inria.fr [192.134.164.104]) by walapai.inria.fr (8.13.6/8.13.6) with ESMTP id p2HGaq6J001101 for ; Thu, 17 Mar 2011 17:36:53 +0100 X-IronPort-AV: E=Sophos;i="4.63,200,1299452400"; d="scan'208";a="78594198" Received: from chercheur-120.msr-inria.inria.fr (HELO [10.0.1.2]) ([193.55.250.120]) by mail3-relais-sop.national.inria.fr with ESMTP/TLS/AES128-SHA; 17 Mar 2011 17:36:47 +0100 Content-Type: text/plain; charset=us-ascii Mime-Version: 1.0 (Apple Message framework v1082) From: Damien Doligez In-Reply-To: <057400AC-9E39-45CC-AB7A-35C67C339F83@math.harvard.edu> Date: Thu, 17 Mar 2011 17:36:47 +0100 Message-Id: <0B1C84C5-3C4A-41B9-862B-FF913DEAA8C0@inria.fr> References: <057400AC-9E39-45CC-AB7A-35C67C339F83@math.harvard.edu> To: OCaml mailing list X-Mailer: Apple Mail (2.1082) Content-Transfer-Encoding: 8bit X-MIME-Autoconverted: from quoted-printable to 8bit by walapai.inria.fr id p2HGaq6J001101 Subject: Re: [Caml-list] obj magic performance and other questions On 2011-03-15, at 17:05, Nicolas Ojeda Bar wrote: > let rec2_b x = > match x.children with > | Rec2 r -> r.b > | _ -> assert false > > This is not very efficient. I can use Obj.magic to access that same field as > follows: > > let rec2_b x = > Obj.obj (Obj.field (Obj.field (Obj.repr x.children 0) 0)) > > My question is: is this use of Obj safe? and is this compiled to (two) simple > array accesses? Or is Obj.obj doing something behind the scenes? Not safe. Your first version of rec2_b is safe: it throws an exception when the "downcast" fails. With your second version, anything can happen if the argument is not a rec2 (program crash, wrong result, silent failure, strange side effects, correct result, whatever). Also, as others have noted, the Obj version might actually do more tests than the proper one (I can't be bothered to check exactly). -- Damien