swift中静态函数和单例类之间的区别 [英] Difference between static function and singleton class in swift

查看:113
本文介绍了swift中静态函数和单例类之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类,其中将保留所有实用程序方法,并且这些方法将在整个应用程序中使用。

问题:1

创建一个单例类并保留所有必要的方法或者我应该创建一个所有函数都是静态的类是不错的。

问题:2

swift上面两种方法的主要区别是什么?

问题:3

它会如何影响iOS中的性能?

I want to create a class where all utility methods will be kept and these methods will be used throughout the app.
Problem:1
Is it good to create a singleton class and keep all necessary methods there or should I create a class where all function will be static.
Problem:2
What is main difference between above two approaches in swift ?
Problem:3
How it will impact performance in iOS?

推荐答案

当然这听起来令人困惑,可以辩论。但是,从最佳实践中我可以提出一些建议。

Sure this sounds confusing and can be debated. However, from the best practices i can put some suggestions.

Singleton 通常用于创建资源密集型和一个计时器初始化,例如:数据库连接器,登录处理程序等。

Singleton is usually used to create a resource intensive and one timer initialisation for instance: a database connector, login handler and such.

实用程序类是只有静态函数和变量的类。它不应该处理异步任务和昂贵的资源处理,如打开数据库连接器。

Utility class are classes that only have static functions and variables. It should not deal with async task and expensive resource handling like opening a database connector.

在您的情况下,如果实用程序正在执行一些资源密集型过程,那么最好将其包装在单例中。如果没有,那么我认为类中的静态函数更好。这也是因为,Swift将使用静态调度在类中调度所有静态函数。虽然Swift喜欢优化,但在Singleton中这不可能是真的。

In your case, if the utility is doing some resource intensive process its better to wrap in a singleton. If not, then Static functions in a class is better in my opinion. This is so also because, Swift will dispatch all static functions in a class using static dispatch. Whereas this cannot be true in Singleton although Swift likes to optimizes.

就使用Objective-C运行时而言,Static Dispatch比Dynamic Dispatch快4倍。对于斯威夫特来说也是如此。但是,动态调度只需4纳秒。

Static Dispatch are 4 times faster than Dynamic Dispatch as far as Objective-C runtime is used. This is true for swift too. However, it only takes 4 nano seconds to dispatch Dynamiclly.

我希望这能让你清楚。

I hope this makes you clear.

这篇关于swift中静态函数和单例类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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