Why does class handle outperform other ways of passing arguments to function?

2 views (last 30 days)
I was starting to familiarize myself with the differences between structs, value classes and handle classes, as well as with the optimizations MATLAB performs to avoid unnecessary copying of data.
I wrote a small sample program that tests the time it takes to pass these different data containers (structs, value classes, handle classes), filled with a large matrix, as arguments to a function, and I did that for a read, write and write&reassign function. These were the results (partially as expected, partially not):
  • Reading is equally fast for structs, value classes and handle classes, as MATLAB's optimization avoids copying the data
  • Writing is slow for structs and value classes, as MATLAB copies the data, while handle classes are faster as they explicitly don't make copies. Of course, the faster behaviour of handle classes isn't a fair comparison here, as the results of the writing differ wrt the case of structs and value classes.
  • Writing&reassigning is equally fast for all of them, yet much slower then reading.
BUT:
  • When writing or writing&reassigning, functions that are given handle class arguments show a large performance leap from the second time these functions are called: writing suddenly becomes as fast as reading, which is a speedup of about a factor 1000-10000.
I can't explain this. If this has something to do with the just-in-time compilation, why is the behaviour different for handle classes wrt value classes or structures?
Here is a sample of the observed timings for the different cases. The full script + output can be found here: https://gist.github.com/asparc/c6597c70b43a493cca1428af77f9304c
Read
====
struct: 0.001657
struct: 0.000061
class: 0.001487
class: 0.000059
handle: 0.001249
handle: 0.000055
Write
=====
struct: 2.339701
struct: 2.372296
class: 2.333061
class: 2.352433
handle: 0.425259
handle: 0.000089
Write & re-assign
=================
struct: 0.419934
struct: 0.412815
class: 0.414880
class: 0.411838
handle: 0.000737
handle: 0.000062

Answers (0)

Categories

Find more on Argument Definitions in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!