scrapper / fit4ruby

Fit4Ruby is a Ruby library to read and write FIT files.
GNU General Public License v2.0
26 stars 17 forks source link

performance improvement: avoid superfluous `attr_accessor` creation #33

Closed pvdb closed 2 months ago

pvdb commented 3 months ago

I noticed that processing a large amount of FIT files was quite slow, so did a bit of profiling.

Using ruby-prof revealed that a lot of time was spent in Module#attr_accessor, creating the attribute accessor methods for the fields of the various data record classes.

A FIT file containing 104 Fit4Ruby::Record instances for example, would call Fit4Ruby::Record#attr_accessor 104 times for each field of that class whereas it only needs to call it once (per class, per field).

The fix is quite straightforward (see diff) and makes reading/processing FIT files almost 20% faster! :tada:

Benchmarking the processing of a directory containing 78 FIT files on the master branch and the feature branch respectively illustrates the performance improvement:

$ git rev-diff master refactor_attr_accessor_creation ruby benchmark_fit4ruby.rb
--- git checkout master && { ruby benchmark_fit4ruby.rb ; } ;
+++ git checkout refactor_attr_accessor_creation && { ruby benchmark_fit4ruby.rb ; } ;
@@ -1 +1 @@
- 78 FIT files processed in 22.03 seconds (avg: 0.28s/file).
+ 78 FIT files processed in 18.64 seconds (avg: 0.24s/file).
$ _
scrapper commented 2 months ago

That's an awesome find! Great work! Thanks!