Understanding the performance benefits of dispatch

Using a singleton type is nice because we can avoid writing conditional branches. Another side benefit is that performance can be greatly improved. An interesting example can be found in the ntuple function from Julia's Base package.

The ntuple function is used to create a tuple of N elements by applying a function over the sequence of 1 to N. For example, we can create a tuple of even numbers as follows:

The first argument is an anonymous function that doubles the value. Since we specified 10 in the second argument, it mapped over the range of 1 to 10 and gave us 2, 4, 6, ... 20. If we ...

Get Hands-On Design Patterns and Best Practices with Julia now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.