是否创建单独的功能,而不是一个大的处理时间? [英] Does creating separate functions instead of one big one slow processing time?

查看:67
本文介绍了是否创建单独的功能,而不是一个大的处理时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Google App Engine环境中工作,并使用Python进行编程。我正在创建一个基本上生成随机数字/字母字符串的函数,然后将其存储到memcache中。

  def generate_random_string():
#返回一个随机的6位长字符串

def check_and_store_to_memcache():
randomstring = generate_random_string()
对memcache进行检查
#if ok,然后用另一个值存储键值
#if不正确,运行generate_random_string()再次检查。

创建两个函数而不是一个大函数会影响性能吗?我更喜欢两个,因为它更好地符合我的想法,但不要介意将它们结合起来,如果这是最佳实践。 解决方案

关注能够阅读和轻松理解你的代码。



一旦你完成了这个任务,如果你有性能问题,那么看看可能是什么原因造成的。

大多数包含python的语言在进行方法调用时往往会有相当低的开销。把这些代码放到一个函数中并不会(显着地)改变性能指标 - 我想你的随机数生成可能是大部分时间,而不是2个函数。


这就是说,分割函数确实对性能有一个(非常非常小的)影响。不过,我会这样想 - 它可能会让你在高速公路上以每小时80英里的速度行驶到79.99英里/小时(你永远不会注意到)。要注意的重要事项是避免红绿灯和交通堵塞,因为它们会让你不得不完全停止......


I'm working in the Google App Engine environment and programming in Python. I am creating a function that essentially generates a random number/letter string and then stores to the memcache.

def generate_random_string():
# return a random 6-digit long string

def check_and_store_to_memcache():
    randomstring = generate_random_string()
    #check against memcache
    #if ok, then store key value with another value
    #if not ok, run generate_random_string() again and check again.

Does creating two functions instead of just one big one affect performance? I prefer two, as it better matches how I think, but don't mind combining them if that's "best practice".

解决方案

Focus on being able to read and easily understand your code.

Once you've done this, if you have a performance problem, then look into what might be causing it.

Most languages, python included, tend to have fairly low overhead for making method calls. Putting this code into a single function is not going to (dramatically) change the performance metrics - I'd guess that your random number generation will probably be the bulk of the time, not having 2 functions.

That being said, splitting functions does have a (very, very minor) impact on performance. However, I'd think of it this way - it may take you from going 80 mph on the highway to 79.99mph (which you'll never really notice). The important things to watch for are avoiding stoplights and traffic jams, since they're going to make you have to stop altogether...

这篇关于是否创建单独的功能,而不是一个大的处理时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆