Skip to content

Changed allocation function to mallocPlainForeignPtr - #40

Closed
VyacheslavHashov wants to merge 1 commit into
lpeterse:0.8.x.xfrom
VyacheslavHashov:alloc-foreignptr
Closed

VyacheslavHashov wants to merge 1 commit into
lpeterse:0.8.x.xfrom
VyacheslavHashov:alloc-foreignptr

Conversation

@VyacheslavHashov

@VyacheslavHashov VyacheslavHashov commented Feb 11, 2017 •

Copy link
Copy Markdown
Contributor

Allocation with mallocPlainForeignPtr is usually 2-2.5x faster than with mallocBytes.

module Main where

import Criterion.Main
import qualified Data.ByteString.Unsafe as B
import qualified Data.ByteString.Internal as B

import Foreign
import GHC.ForeignPtr (mallocPlainForeignPtrBytes)

usualMalloc = do
    ptr <- mallocBytes 4096
    B.unsafePackMallocCStringLen (ptr, 4096)
    pure ()

foreignPtrMalloc = do
    ptr <- mallocPlainForeignPtrBytes 4096
    pure $ B.fromForeignPtr ptr 0 4096
    pure ()
benchmarking Allocator/malloc
time                 138.5 ns   (138.0 ns .. 139.1 ns)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 138.5 ns   (138.1 ns .. 139.0 ns)
std dev              1.522 ns   (944.3 ps .. 2.120 ns)
variance introduced by outliers: 10% (moderately inflated)

benchmarking Allocator/foreignPtr
time                 53.63 ns   (53.46 ns .. 53.86 ns)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 53.52 ns   (53.38 ns .. 53.77 ns)
std dev              640.0 ps   (408.1 ps .. 1.015 ns)
variance introduced by outliers: 12% (moderately inflated)

Influence of different GC options:
foreignPtr.pdf
malloc.pdf

@lpeterse

Copy link
Copy Markdown
Owner

Wow, thank you :-) I did not know this.
Grant me some days to validate the changes, but I'm more than happy to merge it in then.

@lpeterse lpeterse added this to the Release 0.8.0.0 milestone Feb 21, 2017
@lpeterse

Copy link
Copy Markdown
Owner

So, I have validated that change. It is far better than the current implementation.
Also, I finally found the ByteString creation functions I was looking for. Using createUptoN :: Int -> (Ptr Word8 -> IO Int) -> IO ByteString from the ByteString.Internal module should be even more concise and clear.

@lpeterse

Copy link
Copy Markdown
Owner

I cherry-picked the commit into 0.8.0.0.

@lpeterse lpeterse closed this Feb 25, 2017
sternenseemann pushed a commit to sternenseemann/haskell-socket that referenced this pull request Mar 4, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants