我在 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 库并得到了相同的结果。