Version française
Home     About     Download     Resources     Contact us    
Browse thread
questions about costs of nativeint vs int
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Alain Frisch <frisch@c...>
Subject: Re: Cost of polymorphic variants over normal ones.
On Thu, 11 Jan 2001, Sven LUTHER wrote:

> A (somewhat) related question would be, what is the cost of polymorphic
> variants compared to noarmal ones ?
> 
> The normal variants are coded as integers, and using them is fast, while
> polymorphic variants use some kind of hash functionn, but very simple.

AFAIK, the hashing is done only during the compilation (or explicitly
by external C functions). For instance (output of ocaml -dinstr):
# function `ABC -> 10 | `DEF -> 20;;
        closure L1, 0
        return 1
L1:     const 3247170
        push
        acc 1
        eqint
        branchifnot L2
        const 10
        return 1
L2:     const 20
        return 1

> If i use a datatype that i will be pattern matching very often and i want it
> to be quick, how much is the overhead of using polymorphic patterns over
> noraml ones ?

There may be a small overhead because the variants tags are large, so
the compiler can't use the "switch" instruction of the abstract machine.
Compare with (type t = ABC | DEF):
# function ABC -> 10 | DEF -> 20;;
        closure L1, 0
        return 1
L1:     acc 0
        switch 3 2/
L3:     const 10
        return 1
L2:     const 20
        return 1

For the native code, the difference is less visible (ocamlopt -S):
.L102:
        cmpl    $6494341, %eax
        jne     .L101
        movl    $21, %eax
        ret
.L101:
        movl    $41, %eax
        ret

and:

.L105:
        sarl    $1, %eax
        testl   %eax, %eax
        je      .L104
        movl    $41, %eax
        ret
.L104:
        movl    $21, %eax
        ret

(I think the new compilation scheme for pattern matching doesn't affect
these cases).

For more complex case, small value for tags allow optimizations. (see for
instance the assembler code produced for:
function `ABC -> 10 | `DEF -> 20 | `GHI -> 30;;
type t = ABC | DEF | GHI;;
function ABC -> 10 | DEF -> 20 | GHI -> 30;;
)


-- 
  Alain Frisch