通过C#使用Advanced-CSharp-Messenger

Advanced CSharp Messenger 属于C#事件的一种。
维基百科中由详细的说明<http://wiki.unity3d.com/index.php?title=Advanced_CSharp_Messenger上周的一天刚巧有朋友问到我这一块的知识,那么我研究出来将它贴在博客中,帮助了他也帮助我自己!哇咔咔。

Advanced CSharp Messenger的特点可以将游戏对象做为参数发送。到底Advanced CSharp
Messenger有什么用呢?先创建一个立方体对象,然后把Script脚本绑定在这个对象中。脚本中有一个方法叫DoSomething()。

写一段简单的代码,通常我们在调用方法的时候需要这样来写。

C#

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
private Script script;



void Awake()



{



GameObject cube = GameObject.Find("Cube");



script = cube.GetComponent<Script();



}








void Update()



{



if(Input.GetMouseButtonDown(0))



{



script.DoSomething();



}



}

代码比较简单,我就不注释了。
原理就是先获取游戏对象,接着获取脚本组件对象,最后通过脚本组件对象去调用对应脚本中的方法,这样的调用方法我们称之为直接调用。

这个例子中我只调用了一个对象的方法,如果说有成千上万个对象,那么这样调用是不是感觉自己的代码非常的丑?因为你需要一个一个的获取对象然后获取脚本组件然后在调用方法。。。。。
(想想都恐怖!!)

下面我们在用Advanced CSharp Messenger来实现事件的调用。按照维基百科中首先把Message.cs
和Callback.cs拷贝在你的工程中。

CallBack.cs

C#

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
public delegate void Callback();



public delegate void Callback<T(T arg1);



public delegate void Callback<T, U(T arg1, U arg2);



public delegate void Callback<T, U, V(T arg1, U arg2, V arg3);

**Message.cs**

C#

/*



* Advanced C# messenger by Ilya Suzdalnitski. V1.0



*



* Based on Rod Hyde's "CSharpMessenger" and Magnus Wolffelt's
"CSharpMessenger Extended".



*



* Features:



* Prevents a MissingReferenceException because of a reference to a destroyed
message handler.



* Option to log all messages



* Extensive error detection, preventing silent bugs



*



* Usage examples:



1\. Messenger.AddListener<GameObject("prop collected", PropCollected);



   Messenger.Broadcast<GameObject("prop collected", prop);



2\. Messenger.AddListener<float("speed changed", SpeedChanged);



   Messenger.Broadcast<float("speed changed", 0.5f);



*



* Messenger cleans up its evenTable automatically upon loading of a new
level.



*



* Don't forget that the messages that should survive the cleanup, should be
marked with Messenger.MarkAsPermanent(string)



*



*/








//#define LOG_ALL_MESSAGES



//#define LOG_ADD_LISTENER



//#define LOG_BROADCAST_MESSAGE



#define REQUIRE_LISTENER








using System;



using System.Collections.Generic;



using UnityEngine;








static internal class Messenger {



#region Internal variables








//Disable the unused variable warning



#pragma warning disable 0414



//Ensures that the MessengerHelper will be created automatically upon start
of the game.



static private MessengerHelper messengerHelper = ( new
GameObject("MessengerHelper") ).AddComponent< MessengerHelper ();



#pragma warning restore 0414








static public Dictionary<string, Delegate eventTable = new
Dictionary<string, Delegate();








//Message handlers that should never be removed, regardless of calling
Cleanup



static public List< string permanentMessages = new List< string ();



#endregion



#region Helper methods



//Marks a certain message as permanent.



static public void MarkAsPermanent(string eventType) {



#if LOG_ALL_MESSAGES



Debug.Log("Messenger MarkAsPermanent \t\"" + eventType + "\"");



#endif








permanentMessages.Add( eventType );



}








static public void Cleanup()



{



#if LOG_ALL_MESSAGES



Debug.Log("MESSENGER Cleanup. Make sure that none of necessary listeners are
removed.");



#endif








List< string messagesToRemove = new List<string();








foreach (KeyValuePair<string, Delegate pair in eventTable) {



bool wasFound = false;








foreach (string message in permanentMessages) {



if (pair.Key == message) {



wasFound = true;



break;



}



}








if (!wasFound)



messagesToRemove.Add( pair.Key );



}








foreach (string message in messagesToRemove) {



eventTable.Remove( message );



}



}








static public void PrintEventTable()



{



Debug.Log("\t\t\t=== MESSENGER PrintEventTable ===");








foreach (KeyValuePair<string, Delegate pair in eventTable) {



Debug.Log("\t\t\t" + pair.Key + "\t\t" + pair.Value);



}








Debug.Log("\n");



}



#endregion








#region Message logging and exception throwing



    static public void OnListenerAdding(string eventType, Delegate
listenerBeingAdded) {



#if LOG_ALL_MESSAGES || LOG_ADD_LISTENER



Debug.Log("MESSENGER OnListenerAdding \t\"" + eventType + "\"\t{" +
listenerBeingAdded.Target + " - " + listenerBeingAdded.Method + "}");



#endif








        if (!eventTable.ContainsKey(eventType)) {



            eventTable.Add(eventType, null );



        }








        Delegate d = eventTable[eventType];



        if (d != null && d.GetType() != listenerBeingAdded.GetType()) {



            throw new ListenerException(string.Format("Attempting to add
listener with inconsistent signature for event type {0}. Current listeners
have type {1} and listener being added has type {2}", eventType,
d.GetType().Name, listenerBeingAdded.GetType().Name));



        }



    }








    static public void OnListenerRemoving(string eventType, Delegate
listenerBeingRemoved) {



#if LOG_ALL_MESSAGES



Debug.Log("MESSENGER OnListenerRemoving \t\"" + eventType + "\"\t{" +
listenerBeingRemoved.Target + " - " + listenerBeingRemoved.Method + "}");



#endif








        if (eventTable.ContainsKey(eventType)) {



            Delegate d = eventTable[eventType];








            if (d == null) {



                throw new ListenerException(string.Format("Attempting to
remove listener with for event type \"{0}\" but current listener is null.",
eventType));



            } else if (d.GetType() != listenerBeingRemoved.GetType()) {



                throw new ListenerException(string.Format("Attempting to
remove listener with inconsistent signature for event type {0}. Current
listeners have type {1} and listener being removed has type {2}", eventType,
d.GetType().Name, listenerBeingRemoved.GetType().Name));



            }



        } else {



            throw new ListenerException(string.Format("Attempting to remove
listener for type \"{0}\" but Messenger doesn't know about this event type.",
eventType));



        }



    }








    static public void OnListenerRemoved(string eventType) {



        if (eventTable[eventType] == null) {



            eventTable.Remove(eventType);



        }



    }








    static public void OnBroadcasting(string eventType) {



#if REQUIRE_LISTENER



        if (!eventTable.ContainsKey(eventType)) {



            throw new BroadcastException(string.Format("Broadcasting message
\"{0}\" but no listener found. Try marking the message with
Messenger.MarkAsPermanent.", eventType));



        }



#endif



    }








    static public BroadcastException
CreateBroadcastSignatureException(string eventType) {



        return new BroadcastException(string.Format("Broadcasting message
\"{0}\" but listeners have a different signature than the broadcaster.",
eventType));



    }








    public class BroadcastException : Exception {



        public BroadcastException(string msg)



            : base(msg) {



        }



    }








    public class ListenerException : Exception {



        public ListenerException(string msg)



            : base(msg) {



        }



    }



#endregion








#region AddListener



//No parameters



    static public void AddListener(string eventType, Callback handler) {



        OnListenerAdding(eventType, handler);



        eventTable[eventType] = (Callback)eventTable[eventType] + handler;



    }








//Single parameter



static public void AddListener<T(string eventType, Callback<T handler) {



        OnListenerAdding(eventType, handler);



        eventTable[eventType] = (Callback<T)eventTable[eventType] +
handler;



    }








//Two parameters



static public void AddListener<T, U(string eventType, Callback<T, U
handler) {



        OnListenerAdding(eventType, handler);



        eventTable[eventType] = (Callback<T, U)eventTable[eventType] +
handler;



    }








//Three parameters



static public void AddListener<T, U, V(string eventType, Callback<T, U, V
handler) {



        OnListenerAdding(eventType, handler);



        eventTable[eventType] = (Callback<T, U, V)eventTable[eventType] +
handler;



    }



#endregion








#region RemoveListener



//No parameters



    static public void RemoveListener(string eventType, Callback handler) {



        OnListenerRemoving(eventType, handler);



        eventTable[eventType] = (Callback)eventTable[eventType] - handler;



        OnListenerRemoved(eventType);



    }








//Single parameter



static public void RemoveListener<T(string eventType, Callback<T handler)
{



        OnListenerRemoving(eventType, handler);



        eventTable[eventType] = (Callback<T)eventTable[eventType] -
handler;



        OnListenerRemoved(eventType);



    }








//Two parameters



static public void RemoveListener<T, U(string eventType, Callback<T, U
handler) {



        OnListenerRemoving(eventType, handler);



        eventTable[eventType] = (Callback<T, U)eventTable[eventType] -
handler;



        OnListenerRemoved(eventType);



    }








//Three parameters



static public void RemoveListener<T, U, V(string eventType, Callback<T, U,
V handler) {



        OnListenerRemoving(eventType, handler);



        eventTable[eventType] = (Callback<T, U, V)eventTable[eventType] -
handler;



        OnListenerRemoved(eventType);



    }



#endregion








#region Broadcast



//No parameters



    static public void Broadcast(string eventType) {



#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE



Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") +
"\t\t\tInvoking \t\"" + eventType + "\"");



#endif



        OnBroadcasting(eventType);








        Delegate d;



        if (eventTable.TryGetValue(eventType, out d)) {



            Callback callback = d as Callback;








            if (callback != null) {



                callback();



            } else {



                throw CreateBroadcastSignatureException(eventType);



            }



        }



    }








//Single parameter



    static public void Broadcast<T(string eventType, T arg1) {



#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE



Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") +
"\t\t\tInvoking \t\"" + eventType + "\"");



#endif



        OnBroadcasting(eventType);








        Delegate d;



        if (eventTable.TryGetValue(eventType, out d)) {



            Callback<T callback = d as Callback<T;








            if (callback != null) {



                callback(arg1);



            } else {



                throw CreateBroadcastSignatureException(eventType);



            }



        }



}








//Two parameters



    static public void Broadcast<T, U(string eventType, T arg1, U arg2) {



#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE



Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") +
"\t\t\tInvoking \t\"" + eventType + "\"");



#endif



        OnBroadcasting(eventType);








        Delegate d;



        if (eventTable.TryGetValue(eventType, out d)) {



            Callback<T, U callback = d as Callback<T, U;








            if (callback != null) {



                callback(arg1, arg2);



            } else {



                throw CreateBroadcastSignatureException(eventType);



            }



        }



    }








//Three parameters



    static public void Broadcast<T, U, V(string eventType, T arg1, U arg2,
V arg3) {



#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE



Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") +
"\t\t\tInvoking \t\"" + eventType + "\"");



#endif



        OnBroadcasting(eventType);








        Delegate d;



        if (eventTable.TryGetValue(eventType, out d)) {



            Callback<T, U, V callback = d as Callback<T, U, V;








            if (callback != null) {



                callback(arg1, arg2, arg3);



            } else {



                throw CreateBroadcastSignatureException(eventType);



            }



        }



    }



#endregion



}








//This manager will ensure that the messenger's eventTable will be cleaned
up upon loading of a new level.



public sealed class MessengerHelper : MonoBehaviour {



void Awake ()



{



DontDestroyOnLoad(gameObject);



}








//Clean up eventTable every time a new level loads.



public void OnDisable() {



Messenger.Cleanup();



}



}

然后就可以开始使用了,Messager.Broadcast()这样就好比我们发送了一条广播。

C#

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
void Update()



{



if(Input.GetMouseButtonDown(0))



{



Messenger.Broadcast("Send");



}



}

在需要这条广播的类中来接受它,同样是刚刚说的Script类。接受广播的标志是
Messager.AddListener()参数1表示广播的名称,参数2表示广播所调用的方法。

C#

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
using UnityEngine;



using System.Collections;








public class Script : MonoBehaviour {








void Awake()



{



Messenger.AddListener( "Send", DoSomething );



}



public void DoSomething()



{



Debug.Log("DoSomething");



}



}

这样一来,只要发送名称为”Send”的方法,就可以在别的类中接收它了。

我们在说说如何通过广播来传递参数,这也是那天那个哥们主要问我的问题。(其实是维基百科上写的不是特别特别的清楚,那哥们误解了)在Callback中可以看出参数最多可以是三个,参数的类型是任意类型,也就是说我们不仅能传递
int float bool 还能传递gameObject类型。

如下所示,发送广播的时候传递了两个参数,参数1是一个游戏对象,参数2是一个int数值。

C#

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
void Update()



{



if(Input.GetMouseButtonDown(0))



{



GameObject cube = GameObject.Find("Cube");



Messenger.Broadcast<GameObject,int("Send",cube,1980);



}



}

然后是接受的地方 参数用 <存在一起。游戏对象也可以完美的传递。

C#

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
using UnityEngine;



using System.Collections;








public class Script : MonoBehaviour {








void Awake()



{



Messenger.AddListener<GameObject,int( "Send", DoSomething );



}



public void DoSomething(GameObject obj,int i)



{



Debug.Log("name " + obj.name + " id =" + i);



}



}

如果传递一个参数

两个参数 <T,T>

三个参数 <T,T,T>

怎么样使用起来还是挺简单的吧?

我觉得项目中最好不要大量的使用代理事件这类的方法(根据需求而定),虽然可以让你的代码非常的简洁,但是它的效率不高大概比直接调用慢5-倍左右吧,就好比美好的东西一定都有瑕疵一样。
还记得Unity自身也提供了一种发送消息的方法吗?,用过的都知道效率也非常低下,虽然我们看不到它具体实现的源码是如何实现的,但是我觉得原理可能也是这样的。
欢迎和大家一起讨论与学习。

文件I-O优化技巧

一般来说,所有工程都会有对文件进行读写的操作。如果你不仅是要存储少量字节(例如JSON文件),就有必要考虑性能问题了。因为这种情况下很容易写出低效率的文件读写代码,而且编译器和Unity都无法帮助你优化。今天这篇文章将分享文件读写代码中一些常见的误区,希望对大家有所帮助。

.NET
API提供了很多完善的写入文件系统相关的类。Stream抽象类和其子类FileStream,还有File类,带有静态函数Open以及很方便的读写函数如BinaryReader和BinaryWriter。C#语言本身提供了using语法可以方便地关闭文件流、文件读写对象实例和文件句柄。这类代码使用便利,安全系数高,容易实现:

基本来说,文件操作可以归纳为以下五个步骤:

打开文件:File.Open

读取字节:stream.Read

写入字节:stream.Write

查询位置: stream.Position 或 stream.Seek

关闭文件:stream.Dispose 或 stream.Close

如果反编译FileStream类,你会发现stream.Position和stream.Seek其实没有什么区别,仅仅是API叫法上的不同。还有,stream.Dispose和stream.Close也基本上没什么区别,都能关掉文件。

得益于streams,readers,writers的便利性,想要测试它们的性能也很方便。进行读写操作只需调用一个函数即可,但这些读写操作函数的性能消耗可大不相同。接下来我针对这些不同的读写方式写了一个测试程序,下面是程序将要做的工作:

写入20MB,每次写入4KB的数据块

写入20MB,每次写入1字节

读取20MB,每次读取4KB的数据块

读取20MB,每次读取1字节

数次查找流的某个位置,次数与数据块的读写次数相同

数次打开某个文件,次数与数据块的读写次数相同

测试脚本如下:

新建Unity工程,在Assets目录下新建TestScript.cs脚本并复制以上代码。然后在默认的空场景中将TestScript附加到Camera游戏对象上,最后编译。注意编译平台使用64位,在非Development模式下编译,画质设置为最快,分辨率设为最低(640x480)。测试环境如下:

2.3 Ghz Intel Core i7-3615QM

Mac OS X 10.11.2

Apple SSD SM256E, HFS+ format

Unity 5.3.0f4, Mac OS X Standalone, x86_64, non-development

640×480, Fastest, Windowed

测试结果如下:

真是有着天壤之别,因此我单独提取出了最快的三个数据,得到了第二张图表。

可以看出,以数据块的方式进行读写操作的效率非常之高。虽然你可能不会一个一个字节地去写,但却有可能以4字节(整数)或类似大小为数据块单位进行写入操作。所以尽可能以较大的数据块为单位进行操作,这将提高38倍的写入效率,205倍的读取效率!

流查找(不论设置Position或调用Seek)不会进行字节读写,但这种操作是有代价的,虽然没有其它类型的操作那样多,它需要相当于读取4KB数据块三分之一的资源。所以最好避免这种查找操作,尽量线性读写文件,这样才能在各层面最大限度地发挥缓存的优势。

最后,打开或关闭文件同样不需要读取任何字节,但需要的时间会很长。事实证明,非常之长!打开和关闭文件需要的时间是以字节块写入整个文件所需时间的6.5倍,是字节块方式读取整个文件所需时间的40倍。考虑到读写操作的重要性,以及打开和关闭文件是操作系统的唯一需求,所以,除非特别需要,不要打开关闭文件。而且操作大文件要比操作多个小文件更好。

以上包括了关于I/O性能的一些建议,如有疑问,欢迎来下方评论区留言。

本文来源于:jacksondunstan.com

原作者:Jackson Dunstan

C#字符串连接的效率问题

C#字符串连接常用的四种方式:StringBuilder、+、string.Format、List

1.+的方式

1
2
string sql = "update tableName set int1=" + int1.ToString() + ",int2=" +
int2.ToString() + ",int3=" + int3.ToString() + " where id=" + id.ToString();

编译器会优化为:

1
2
3
string sql = string.Concat(new string[] { "update tableName set int1=",
int1.ToString(), ",int2=", int2.ToString(), ",int3=", int3.ToString(), " where
id=", id.ToString() });

下面是string.Concat的实现:

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
public static string Concat(params string[] values)

{

int totalLength = 0;



if (values == null)



{



throw new ArgumentNullException("values");



}



string[] strArray = new string[values.Length];



for (int i = 0; i < values.Length; i++)



{



string str = values[i];



strArray[i] = (str == null) ? Empty : str;



totalLength += strArray[i].Length;



if (totalLength < 0)



{



throw new OutOfMemoryException();



}



}



return ConcatArray(strArray, totalLength);



}



private static string ConcatArray(string[] values, int totalLength)



{



string dest = FastAllocateString(totalLength);



int destPos = 0;



for (int i = 0; i < values.Length; i++)



{



FillStringChecked(dest, destPos, values[i]);



destPos += values[i].Length;



}



return dest;



}



private static unsafe void FillStringChecked(string dest, int destPos,
string src)



{



int length = src.Length;



if (length(dest.Length - destPos))



{



throw new IndexOutOfRangeException();



}



fixed (char* chRef = &dest.m_firstChar)



{



fixed (char* chRef2 = &src.m_firstChar)



{



wstrcpy(chRef + destPos, chRef2, length);



}



}



}

先计算目标字符串的长度,然后申请相应的空间,最后逐一复制,时间复杂度为o(n),常数为1。固定数量的字符串连接效率最高的是+。但是字符串的连+不要拆成多条语句,比如:

1
2
3
string sql = "update tableName set int1=";
sql += int1.ToString();
sql += ...

这样的代码,不会被优化为string.Concat,就变成了性能杀手,因为第i个字符串需要复制n-i次,时间复杂度就成了o(n^2)。

2.StringBuilder的方式

如果字符串的数量不固定,就用StringBuilder,一般情况下它使用2n的空间来保证o(n)的整体时间复杂度,常数项接近于2。

因为这个算法的实用与高效,.net类库里面有很多动态集合都采用这种牺牲空间换取时间的方式,一般来说效果还是不错的。

3.string.Format的方式

它的底层是StringBuilder,所以其效率与StringBuiler相似。

# 4.List它可以转换为string[]后使用string.Concat或string.Join,很多时候效率比StringBuiler更高效。

List与StringBuilder采用的是同样的动态集合算法,时间复杂度也是O(n),与StringBuilder不同的是:List的n是字符串的数量,复制的是字符串的引用;StringBuilder的n是字符串的长度,复制的数据。不同的特性决定的它们各自的适应环境,当子串比较大时建议使用List,因为复制引用比复制数据划算。而当子串比较小,比如平均长度小于8,特别是一个一个的字符,建议使用StringBuilder。

总结:

1>固定数量的字符串连接+的效率是最高的;

2>当字符串的数量不固定,并且子串的长度小于8,用StringBuiler的效率高些。

3>当字符串的数量不固定,并且子串的长度大于8,用List的效率高些。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×