-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
63 lines (46 loc) · 3.08 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>zhangyu9050 - GitHub by zhangyu9050</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
<link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">
</head>
<body>
<section class="page-header">
<h1 class="project-name">zhangyu9050 - GitHub</h1>
<h2 class="project-tagline">我虽然不是极客,但有极客的精神</h2>
</section>
<section class="main-content">
<h1>
<a id="objective-c-里消息调用的一个优化技巧" class="anchor" href="#objective-c-%E9%87%8C%E6%B6%88%E6%81%AF%E8%B0%83%E7%94%A8%E7%9A%84%E4%B8%80%E4%B8%AA%E4%BC%98%E5%8C%96%E6%8A%80%E5%B7%A7" aria-hidden="true"><span class="octicon octicon-link"></span></a>Objective-C 里消息调用的一个优化技巧</h1>
<p>这里介绍一个小优化技巧,消息调用优化。一般情况下不需要这么做,在大循环里也许可以用到。我自己就从来没这么用过,不过值得给大家介绍一下。 objc的消息调用有一定cpu损耗在方法查询上,虽然非常小,但是当循环次数多时候,使用objc runtime方法分离开消息查找和调用就个很好的方法。例如下面的代码:</p>
<pre><code>for (int i = 0; i < 100000000; i++)
[someObject messageWithInt:i];
</code></pre>
<p>可以改写成:</p>
<pre><code>SEL theSelector = @selector(messageWithInt:);
IMP theMethod = [someObject methodForSelector:theSelector];
for (int i = 0; i < 100000000; i++)
theMethod (someObject, theSelector, i);
</code></pre>
<p>这样可以让objc方法查找过程只执行1遍。循环内直接调用方法实现即可。</p>
<p>这种方法需要非常注意的一点是,IMP是一个 void* 函数的 typedef 如果调用的函数有返回值,就需要非常谨慎了。你可以使用如下的形式:</p>
<pre><code>typedef float (*MyMethodIMP)(id,SEL,int);
SEL theSel = @selector(messageWithInt:);
MyMethodIMP theMethod = (MyMethodIMP)[someObject methodForSelector:theSel];
float result = 0.0;
for (int i = 0; i < 100000000; i++)
result += theMethod (someObject, theSel, i);
</code></pre>
<p>这种优化方法不适合少次数的方法调用,实际上,分离后少次数调用速度有时候会比传统方法还慢一些。至于多少次适合,以自己做的测试为准。</p>
<p>无论如何,当优化代码时候要格外谨慎。</p>
<footer class="site-footer">
<span class="site-footer-credits">This page was generated by <a href="https://pages.github.com">GitHub Pages</a> using the <a href="https://github.com/jasonlong/cayman-theme">Cayman theme</a> by <a href="https://twitter.com/jasonlong">Jason Long</a>.</span>
</footer>
</section>
</body>
</html>