Skip to Content
C#并发编程经典实例(第2版)
book

C#并发编程经典实例(第2版)

by Stephen Cleary
November 2020
Intermediate to advanced
226 pages
5h 34m
Chinese
Posts & Telecom Press
Content preview from C#并发编程经典实例(第2版)
108
9
9.2
 不可变列表
问题
假设需要一个可以建立索引的数据结构,该结构不会经常更改,并且可以被多个线程安全
访问。
解决方案
列表是一种通用型数据结构,可用于所有种类的应用程序状态。不可变列表确实支持索
引,但需要留意性能特性。它们并不单纯是
List<T>
的替代品。
ImmutableList<T>
支持类似于
List<T>
的方法,如下所示:
ImmutableList<
int
> list = ImmutableList<
int
>.Empty;
list = list.Insert(0, 13);
list = list.Insert(0, 7);
//
13
之前显示
7
foreach
(
int
item
in
list)
Trace.WriteLine(item);
list = list.RemoveAt(1);
该不可变列表的内部组织为二叉树,如此一来,不可变列表实例与其他实例的共享内存可
以最大化。对于某些常见操作,
ImmutableList<T>
List<T>
之间存在性能差异,如表
9-2
所示。
9-2:列表与不可变列表的性能差异
操作
List<T> ImmutableList<T>
添加 均摊
O
(1)
O
(log
N
)
插入
O
(
N
)
O
(log
N
)
移除某项
O
(
N
)
O
(log
N
)
索引
O
(1)
O
(log
N
)
注意,
ImmutableList<T>
的索引操作是
O
(log
N
)
,而不是
O
(1)
,这一点应该很好理解。如果
ImmutableList<T>
替换现有代码中的
List<T> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

解密金融数据

解密金融数据

Justin Pauley
PHP编程:第4版

PHP编程:第4版

Kevin Tatroe, Peter MacIntyre

Publisher Resources

ISBN: 9787115550606