# Speeding up force calculations and mutable structs

**URL:** https://discourse.julialang.org/t/speeding-up-force-calculations-and-mutable-structs/44228
**Category:** Performance
**Created:** [August 4, 2020, 3:41am UTC](https://discourse.julialang.org/t/speeding-up-force-calculations-and-mutable-structs/44228 "2020-08-04T03:41:39Z")
**Posts on this page:** 1
**Showing post:** 14

<div class="post-metadata">

### Author: ![Michael\_Wang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/michael_wang/32/8535_2.png) [@Michael\_Wang](https://discourse.julialang.org/u/Michael_Wang)
#### Post date: [August 4, 2020, 5:08pm UTC](https://discourse.julialang.org/t/speeding-up-force-calculations-and-mutable-structs/44228/14 "2020-08-04T17:08:57Z")

</div>

- I used `@code_warntype` on `compute_pair_interaction!` and got no type issues. I also did the same for a simplified version where I removed all `for` loops and `if` statements (basically chose one `particle` and one `neighbor` and computed the force instead of looping over all of them). `@code_warntype` didn’t output anything bad. I’m not entirely sure this means my code is type-stable because there was an incident in the past where `@code_warntype` came back fine but it turned out that there was a statement like `one_of_many_structs_grouped_under_abstract_type.shared_field` that needed to be rewritten as `....shared_field::Float64` in order to have performant code.

- `@use_threads` is a macro that becomes `Threads.@threads` if `lj.multithreaded` is `true`; otherwise it becomes a normal `for` loop without threads (see [post](https://discourse.julialang.org/t/putting-threads-threads-or-any-macro-in-an-if-statement/41406/9)). With three threads, this gives about a x2 boost to speed compare to a single thread. Note that if I replace `@use_threads lj.multithreaded` with `Threads.@threads`, the performance is nearly identical.

- There are about 17 allocations (2.7 KiB) per function call. 16 of those allocations comes from the threading regardless if I use `@use_threads` or `Threads.@threads`. I haven’t quite found where that remaining allocation comes from, though it seems insignificant. Is it possible for `@time` or `@btime` to miss some allocations in a function?

Edit: I will try Duane\_Wilson’s suggestion with Setfield and see if switching all my structs to immutable has any effect.

---

_[View the full topic](https://discourse.julialang.org/t/speeding-up-force-calculations-and-mutable-structs/44228)._
