创建单独的函数而不是一个大的函数会降低处理时间吗? [英] Does creating separate functions instead of one big one slow processing time?

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

问题描述

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

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.

大多数语言,包括 Python,在进行方法调用时的开销往往相当低.将此代码放入单个函数中不会(显着地)改变性能指标 - 我猜你的随机数生成可能大部分时间都是,没有 2 个函数.

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.

话虽如此,拆分函数确实对性能有(非常非常小的)影响.然而,我会这样想——它可能会把你从高速公路上的 80 英里每小时提高到 79.99 英里每小时(你永远不会真正注意到).需要注意的重要事项是避免红绿灯和交通堵塞,因为它们会让您不得不完全停下来...

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天全站免登陆