# Optimizing dinucleotides count in a DNA sequence type \`LongDNA\`

**URL:** <https://discourse.julialang.org/t/optimizing-dinucleotides-count-in-a-dna-sequence-type-longdna/101583>\
**Category:** Performance\
**Tags:** question, performance, strings, biology\
**Created:** [July 13, 2023, 4:51pm UTC](https://discourse.julialang.org/t/optimizing-dinucleotides-count-in-a-dna-sequence-type-longdna/101583 "2023-07-13T16:51:55Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)\
**Post date:** [July 14, 2023, 1:48pm UTC](https://discourse.julialang.org/t/optimizing-dinucleotides-count-in-a-dna-sequence-type-longdna/101583/11 "2023-07-14T13:48:13Z")

</div>

updating IterTools to the [master](https://discourse.julialang.org/t/why-so-many-allocations-in-the-loop-on-partition/101606/3) you get the following result

```julia

julia> @btime countmap(zip(rseq,@view rseq[begin+1:end]));
  10.757 ms (11 allocations: 1.41 KiB)

julia> @btime countmap(partition(rseq,2,1));
  9.726 ms (9 allocations: 1.33 KiB)

```

if a tighter (5X) time was needed, something like this could be done

```julia

julia> rseq=rand(codeunits("ACGT"),10^6)
1000000-element Vector{UInt8}:
 0x41
 0x41
 0x41
 0x47
 0x54
 0x54
 0x43
 0x41
 0x41
    ⋮
 0x41
 0x54
 0x43
 0x47
 0x41
 0x41
 0x54
 0x47

julia> @btime countmap(reinterpret(UInt16,@view repeat($rseq,inner=2)[2:end-1]))
  1.731 ms (11 allocations: 2.41 MiB)
Dict{UInt16, Int64} with 16 entries:
  0x4341 => 62529
  0x5441 => 62362
  0x4754 => 62289
  0x4743 => 62460
  0x5447 => 62838
  0x4354 => 62691
  0x4143 => 62459
  0x4747 => 62239
  0x4343 => 62486
  0x4347 => 62278
  0x5454 => 62697
  0x4141 => 62259
  0x4154 => 62799
  0x5443 => 62579
  0x4147 => 62333
  0x4741 => 62701

julia> @btime join.(partition(Char.(reinterpret(UInt8,Base.vect(keys(cm)...))),2,2)).=>values(cm)
  3.950 μs (112 allocations: 4.73 KiB)
16-element Vector{Pair{String, Int64}}:
 "AC" => 62529
 "AT" => 62362
 "TG" => 62289
 "CG" => 62460
 "GT" => 62838
 "TC" => 62691
 "CA" => 62459
 "GG" => 62239
 "CC" => 62486
 "GC" => 62278
 "TT" => 62697
 "AA" => 62259
 "TA" => 62799
 "CT" => 62579
 "GA" => 62333
 "AG" => 62701

```

---

_[View the full topic](https://discourse.julialang.org/t/optimizing-dinucleotides-count-in-a-dna-sequence-type-longdna/101583)._
