optimization - Optimising `__getitem__` and `__setitem__` for a sparse array in Python -


I am writing my own sparse (one dimensional) array class, but I'm having issues with some functionality. Shows profiling that a mine disruptions __ getitem __ and __ Setitkm __ deployment, and in particular, it seems that one of the criminals I isinstance may be used . At the moment I have is isinstance in 5 calls for __ getitem __ and I get the following data Seepiarfail (excerpt):

 ncalls tottime percall cumtime percall filename: Linono (function) 86 462 0.076 0.000 0.084 0.000 Sparaseyupitiyueti (__setitem__) 189730 0.147 0.000 0.166 0.000 Sparasejet_ita (__getitem__) 276366 0.028 0.000 0.028 0.000 {underlying method isinstance}  

I __ getitem __ < / Code> applies array access as well as slicing, so I need some types of introspection . ..but i am thinking isinstance is actually the best way to do this?

My __setim __ , on the other hand, does not support the slicing action (and only calls isinstance in any case ), So this is a disadvantage that I can do it fast: per-line profiling data is as follows:

  line # hits time per hit% time line content ===== ================================================== , Key, value): 110 88705 121012 1.4 23.0 If not an estimate (key, int): 111 type type error ('List Su Kank integer must ') 112 113 88705 95 9 05 1.1 18.3 If the key> gt; Self._length: 114 raise index error ('index out of range index') 115 116 88705 85328 1.0 16.2 If the key is & lt; 0: 117 key = self._length + key 118 119 88705 89186 1.0 17.0 If value == self _ Default: 120 35043 37087 1.1 7.1 Key K_net themselves: 121 35042 39359 1.1 7.5 Del self K_sentis [key] 122 Other 123 53 662 57 527 1.1 10.9 Self K_sentis [key] = value   

(I am also ready to accept an answer to suggest an appropriate sharp sparse array Python module. One of my requirements (only key) ability to quick iterate over non-zero entries.) < / P>

To give your immediate reply A question, isinstance () is a slow call the name Global you __ setitem __ () sign, such as:

  def the __setitem __  isinstance = isinstance   

this is converted into a local name to a global name, which runs Time is fast enough to look at. As a bonus, the local name function is bound to the built-in isinstance function in the definition time, so when it is called then there is no overhead to start the variable.

As others have said, however, in the code you show, you probably do not need that call, but to convert this key to any int Can try, or even leave it (However, by adding int = int to your method signature, you can boost some speed, because int is also a global name ...)

But if you are going to check the error, then you should also see if the index is less than zero. What if the length is 50 and the user wants the item -100? : -)

Comments