# Optimal way to speed up class method

**URL:** <https://numba.discourse.group/t/optimal-way-to-speed-up-class-method/196>\
**Category:** Support: How do I do ...?\
**Created:** [August 27, 2020, 12:18pm UTC](https://numba.discourse.group/t/optimal-way-to-speed-up-class-method/196 "2020-08-27T12:18:58Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![stuartarchibald](https://yyz2.discourse-cdn.com/free1/user_avatar/numba.discourse.group/stuartarchibald/32/10_2.png) [@stuartarchibald](https://numba.discourse.group/u/stuartarchibald)\
**Post date:** [August 28, 2020, 9:24am UTC](https://numba.discourse.group/t/optimal-way-to-speed-up-class-method/196/6 "2020-08-28T09:24:00Z")

</div>

Agree, I should indeed have put the specialisation into the ` __init__ ` given the specialisations are solely a function of variables at class instantiation.

> Maybe each time mymethod is called on a new x there really is something compiled …

That’s exactly what’s happening, I wrote something too generalised! Given the per-class specialisation of the compiled code is solely down to values at initialisation time, redesigning this as you suggest prevents this from happening.

What you have in the above is probably about as good as it’ll get, but you can always add `cache=True` into the decorator to save having to compile new ones each time you run the code (presuming the values are the same). Think it’d also be ok to put the generator into the ` __init__ ` or as a `@classmethod` if desirable, e.g.

```auto
from numba import jit
import numpy as np

class MyClass(object):
    def __init__ (self, a, b):
        self.a = a
        self.b = b
        self._method = self.generate(self.a, self.b)

    @classmethod
    def generate(cls, a, b):
        @jit(nopython=True, cache=True)
        def aux(x):
            #*do some complicated computations which involve a and b*
            return (a + b) * x # trivial example expression
        return aux

    def mymethod(self, x):
        return self._method(x)

inst = MyClass(0.1, 1.0)
print(inst.mymethod(2))

inst2 = MyClass(0.1, 2.0)
print(inst2.mymethod(2))

```

Anyway, glad you got something working! 🙂

Also, there’s some general [performance tips here](https://numba.readthedocs.io/en/stable/user/performance-tips.html) that might be worth a read?

---

_[View the full topic](https://numba.discourse.group/t/optimal-way-to-speed-up-class-method/196)._
