简体   繁体   中英

In python why does raising the same exception take more memory than throwing a new exception?

I was profiling some code that raises exceptions to determine which of two approaches was better when I came across some memory usage that seems counter intuitive. Perhaps someone can shed some light. Test1 below raises a new exception 10K times. It takes less memory than raising the same exception 10K times. ???

Python 3.9

from memory_profiler import profile

TEST_COUNT = 10000


class ApplicationException(Exception):
    def __init__(self):
        self.code = 0

@profile
def test1():
    for x in range(TEST_COUNT):
        try:
            raise ApplicationException()
        except:
            pass


@profile
def test2():
    application_exception = ApplicationException()
    for x in range(TEST_COUNT):
        try:
            raise application_exception
        except:
            pass


test1()
test2()

The results were:

Line #    Mem usage    Increment  Occurences   Line Contents
_____________________________________________________________
    10     14.1 MiB     14.1 MiB           1   @profile
    11                                         def test1():
    12     14.1 MiB      0.0 MiB       10001       for x in range(TEST_COUNT):
    13     14.1 MiB      0.0 MiB       10000           try:
    14     14.1 MiB      0.0 MiB       10000               raise ApplicationException()
    15     14.1 MiB      0.0 MiB       10000           except:
    16     14.1 MiB      0.0 MiB       10000               pass
Line #    Mem usage    Increment  Occurences   Line Contents
_____________________________________________________________
    19     14.2 MiB     14.2 MiB           1   @profile
    20                                         def test2():
    21     14.2 MiB      0.0 MiB           1       application_exception = ApplicationException()
    22     14.7 MiB      0.0 MiB       10001       for x in range(TEST_COUNT):
    23     14.7 MiB      0.0 MiB       10000           try:
    24     14.7 MiB      0.5 MiB       10000               raise application_exception
    25     14.7 MiB      0.0 MiB       10000           except:
    26     14.7 MiB      0.0 MiB       10000               pass

Not sure what is going on here. Line 24 incurs some expense in memory. Can someone explain?

In the first test, you are raising a new instance of ApplicationException class but you don't assign it any variable .

However in the second test, you assign a ApplicationException instance to a variable , than raise it. Assigned variables has extra information like name and so on. So, it uses more memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM