Django:递归使用 "request.POST" 缓存?

Django : recursive use of "request.POST" caching?

案例 1案例 2 之间是否存在 速度差异

(假设request.POST包含相当大的数据)


案例一

Class do_something():
     """
     Recursive use of "request.POST"
     """
     foo_1 = request.POST["foo"]
     foo_2 = request.POST["foo"]
     foo_3 = request.POST["foo"]

案例二

Class do_something():
     """
     Save "request.POST" data as a local variable and reuse it repeatedly
     """
     foo = request.POST["foo"]
     foo_1 = foo
     foo_2 = foo
     foo_3 = foo

提前致谢。

是的,第二种情况更快,但您可以忽略这种差异。

我 运行 这些函数在一个相当大的 QueryDict 上执行了一百万次:

>>> import timeit
>>> from django.http import QueryDict
>>> query_string = '&'.join('key%d=%s' % (i, 'xxx'*100*i) for i in range(100))
>>> len(query_string)
1485689
>>> POST = QueryDict(query_string)
>>> def func1():
...     foo_1 = POST['key1']
...     foo_2 = POST['key1']
...     foo_3 = POST['key1']
... 
>>> def func2():
...     foo = POST['key1']
...     foo_1 = foo
...     foo_2 = foo
...     foo_3 = foo
... 
>>> timeit.timeit(func1, number=1000000)
3.6945719718933105
>>> timeit.timeit(func2, number=1000000)
1.3247950077056885