序列化python列表的性能

时间:2013-04-03 04:10:09

标签: python performance wsgi

我在Python中的性能方面遇到了一些麻烦。在我的wsgi应用程序中,我将序列化为json类的列表。这是我的代码:

class Foo (object):
    def __init__(self, id,object_id, name_id,name,val,val2):
        self.id = id
        self.object_id = object_id 
        self.name_id = name_id 
        self.name = name
        self.val = val 
        self.add_val = val2


def application(environ, start_response):
        status = '200 OK'
        q = list()
        response_headers = [('Content-type', "application/json")]
        start_response(status, response_headers)
        for i in range(1,50001):
            p = Foo(str(i),random.random(), 'col_3','col_4','col_5','col_6')
            q.append(p.__dict___)
        return json.dumps(q)

我得到的答案很慢(大约18秒)。然后我重写代码:

class Foo (object):
    def __init__(self, id,object_id, name_id,name,val,val2):
        self.id = id
        self.object_id = object_id 
        self.name_id = name_id 
        self.name = name
        self.val = val 
        self.add_val = val2


def application(environ, start_response):
        status = '200 OK'
        q = list()
        response_headers = [('Content-type', "application/json")]
        start_response(status, response_headers)
        yield '['
        for i in range(1,50001):
            p = Foo(str(i),random.random(), 'col_3','col_4','col_5','col_6')
            yield json.dumps(p.__dict___)
        yield ']'

运行速度更快(约4-6秒)。我不明白为什么。你能解释一下为什么我有这个结果吗? PS我尝试了不同的json libs并得到了相同的结果。

0 个答案:

没有答案