Merge pull request #205 from songleo/master

第18章翻译 初稿
This commit is contained in:
Unknwon
2016-01-04 04:49:20 +08:00
13 changed files with 482 additions and 1 deletions

7
eBook/18.0.md Normal file
View File

@@ -0,0 +1,7 @@
# 18 出于性能考虑的实用代码片段
## 链接
- [目录](directory.md)
- 上一章:[运算符模板和接口](17.4.md)
- 下一节:[字符串](18.1.md)

60
eBook/18.1.md Normal file
View File

@@ -0,0 +1,60 @@
# 18.1 字符串
1如何修改字符串中的一个字符
```go
str:="hello"
c:=[]byte(s)
c[0]='c'
s2:= string(c) // s2 == "cello"
```
2如何获取字符串的子串
```go
substr := str[n:m]
```
3如何使用`for`或者`for-range`遍历一个字符串:
```go
// gives only the bytes:
for i:=0; i < len(str); i++ {
= str[i]
}
// gives the Unicode characters:
for ix, ch := range str {
}
```
4如何获取一个字符串的字节数`len(str)`
如何获取一个字符串的字符数:
最快速:`utf8.RuneCountInString(str)`
5如何连接字符串
最快速:
`with a bytes.Buffer`(参考[章节7.2](07.2.md)
`Strings.Join()`(参考[章节4.7](04.7.md)
使用`+=`
```go
str1 := "Hello "
str2 := "World!"
str1 += str2 //str1 == "Hello World!"
```
6如何解析命令行参数使用`os`或者`flag`包
(参考[例12.4](examples/chapter_12/fileinput.go)
## 链接
- [目录](directory.md)
- 上一节:[出于性能考虑的实用代码片段](18.0.md)
- 下一节:[数组和切片](18.2.md)

23
eBook/18.10.md Normal file
View File

@@ -0,0 +1,23 @@
# 18.10 其他
如何在程序出错时终止程序:
```go
if err != nil {
fmt.Printf(“Program stopping with error %v”, err)
os.Exit(1)
}
```
或者:
```go
if err != nil {
panic(“ERROR occurred: “ + err.Error())
}
```
## 链接
- [目录](directory.md)
- 上一节:[网络和网页应用](18.9.md)
- 下一节:[出于性能考虑的最佳实践和建议](18.11.md)

30
eBook/18.11.md Normal file
View File

@@ -0,0 +1,30 @@
# 18.11 出于性能考虑的最佳实践和建议
1尽可能的使用`:=`去初始化声明一个变量(在函数内部);
2尽可能的使用字符代替字符串
3尽可能的使用切片代替数组
4尽可能的使用数组和切片代替映射详见参考文献15
5如果只想获取切片中某项值不需要值的索引尽可能的使用`for range`去遍历切片,这比必须去查询切片中的每个元素要快一些;
6当数组元素是稀疏的例如有很多`0`值或者空值`nil`),使用映射会降低内存消耗;
7初始化映射时指定其容量
8当定义一个方法时使用指针类型作为方法的接受者
9在代码中使用常量或者标志提取常量的值
10尽可能在需要分配大量内存时使用缓存
11使用缓存模板参考[章节15.7](15.7.md))。
## 链接
- [目录](directory.md)
- 上一节:[其他](18.10.md)
- 下一章:[构建一个完整的应用程序](19.0.md)

50
eBook/18.2.md Normal file
View File

@@ -0,0 +1,50 @@
# 18.2 数组和切片
创建:
`arr1 := new([len]type)`
`slice1 := make([]type, len)`
初始化:
`arr1 := [...]type{i1, i2, i3, i4, i5}`
`arrKeyValue := [len]type{i1: val1, i2: val2}`
`var slice1 []type = arr1[start:end]`
1如何截断数组或者切片的最后一个元素
`line = line[:len(line)-1]`
2如何使用`for`或者`for-range`遍历一个数组(或者切片):
```go
for i:=0; i < len(arr); i++ {
= arr[i]
}
for ix, value := range arr {
}
```
3如何在一个二维数组或者切片`arr2Dim`中查找一个指定值`V`
```go
found := false
Found: for row := range arr2Dim {
for column := range arr2Dim[row] {
if arr2Dim[row][column] == V{
found = true
break Found
}
}
}
```
## 链接
- [目录](directory.md)
- 上一节:[字符串](18.1.md)
- 下一节:[映射](18.3.md)

29
eBook/18.3.md Normal file
View File

@@ -0,0 +1,29 @@
# 18.3 映射
创建: `map1 := make(map[keytype]valuetype)`
初始化: `map1 := map[string]int{"one": 1, "two": 2}`
1如何使用`for`或者`for-range`遍历一个映射:
```go
for key, value := range map1 {
}
```
2如何在一个映射中检测键`key1`是否存在:
`val1, isPresent = map1[key1]`
返回值:键`key1`对应的值或者`0`, `true`或者`false`
3如何在映射中删除一个键
`delete(map1, key1)`
## 链接
- [目录](directory.md)
- 上一节:[数组和切片](18.2.md)
- 下一节:[结构体](18.4.md)

32
eBook/18.4.md Normal file
View File

@@ -0,0 +1,32 @@
# 18.4 结构体
创建:
```go
type struct1 struct {
field1 type1
field2 type2
}
ms := new(struct1)
```
初始化:
```go
ms := &struct1{10, 15.5, "Chris"}
```
当结构体的命名以大写字母开头时,该结构体在包外可见。
通常情况下,为每个结构体定义一个构建函数,并推荐使用构建函数初始化结构体(参考[例10.2](examples/chapter_10/person.go)
```go
ms := Newstruct1{10, 15.5, "Chris"}
func Newstruct1(n int, f float32, name string) *struct1 {
return &struct1{n, f, name}
}
```
## 链接
- [目录](directory.md)
- 上一节:[映射](18.3.md)
- 下一节:[接口](18.5.md)

38
eBook/18.5.md Normal file
View File

@@ -0,0 +1,38 @@
# 18.5 接口
1如何检测一个值`v`是否实现了接口`Stringer`
```go
if v, ok := v.(Stringer); ok {
fmt.Printf("implements String(): %s\n", v.String())
}
```
2如何使用接口实现一个类型分类函数
```go
func classifier(items ...interface{}) {
for i, x := range items {
switch x.(type) {
case bool:
fmt.Printf("param #%d is a bool\n", i)
case float64:
fmt.Printf("param #%d is a float64\n", i)
case int, int64:
fmt.Printf("param #%d is an int\n", i)
case nil:
fmt.Printf("param #%d is nil\n", i)
case string:
fmt.Printf("param #%d is a string\n", i)
default:
fmt.Printf("param #%ds type is unknown\n", i)
}
}
}
```
## 链接
- [目录](directory.md)
- 上一节:[结构体](18.4.md)
- 下一节:[函数](18.6.md)

23
eBook/18.6.md Normal file
View File

@@ -0,0 +1,23 @@
# 18.6 函数
如何使用内建函数`recover`终止`panic`过程(参考[章节13.3](13.3.md)
```go
func protect(g func()) {
defer func() {
log.Println("done")
// Println executes normally even if there is a panic
if x := recover(); x != nil {
log.Printf("run time panic: %v", x)
}
}()
log.Println("start")
g()
}
```
## 链接
- [目录](directory.md)
- 上一节:[接口](18.5.md)
- 下一节:[文件](18.7.md)

52
eBook/18.7.md Normal file
View File

@@ -0,0 +1,52 @@
# 18.7 文件
1如何打开一个文件并读取
```go
file, err := os.Open("input.dat")
if err != nil {
fmt.Printf("An error occurred on opening the inputfile\n" +
"Does the file exist?\n" +
"Have you got acces to it?\n")
return
}
defer file.Close()
iReader := bufio.NewReader(file)
for {
str, err := iReader.ReadString('\n')
if err != nil {
return // error or EOF
}
fmt.Printf("The input was: %s", str)
}
```
2如何通过切片读写文件
```go
func cat(f *file.File) {
const NBUF = 512
var buf [NBUF]byte
for {
switch nr, er := f.Read(buf[:]); true {
case nr < 0:
fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n",
f.String(), er.String())
os.Exit(1)
case nr == 0: // EOF
return
case nr > 0:
if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr {
fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n",
f.String(), ew.String())
}
}
}
}
```
## 链接
- [目录](directory.md)
- 上一节:[函数](18.6.md)
- 下一节:[协程goroutine与通道channel](18.8.md)

116
eBook/18.8.md Normal file
View File

@@ -0,0 +1,116 @@
# 18.8 协程goroutine与通道channel
出于性能考虑的建议:
实践经验表明,如果你使用并行计算获得高于串行运算的效率:在协程内部已经完成的大部分工作,其开销比创建协程和协程间通信还高。
1 出于性能考虑建议使用带缓存的通道:
使用带缓存的通道可以很轻易成倍提高它的吞吐量某些场景其性能可以提高至10倍甚至更多。通过调整通道的容量你可以尝试着更进一步的优化其性能。
2 限制一个通道的数据数量并将它们封装成一个数组:
如果使用通道传递大量单独的数据那么通道将变成性能瓶颈。然而将数据块打包封装成数组在接收端解压数据时性能可以提高至10倍。
创建:`ch := make(chan type,buf)`
1如何使用`for`或者`for-range`遍历一个通道:
```go
for v := range ch {
// do something with v
}
```
2如何检测一个通道`ch`是否关闭:
```go
//read channel until it closes or error-condition
for {
if input, open := <-ch; !open {
break
}
fmt.Printf("%s", input)
}
```
或者使用1自动检测。
3如何通过一个通道让主程序等待直到协程完成
(信号量模式):
```go
ch := make(chan int) // Allocate a channel.
// Start something in a goroutine; when it completes, signal on the channel.
go func() {
// doSomething
ch <- 1 // Send a signal; value does not matter.
}()
doSomethingElseForAWhile()
<-ch // Wait for goroutine to finish; discard sent value.
```
如果希望程序一直阻塞,在匿名函数中省略 `ch <- 1`即可。
4通道的工厂模板以下函数是一个通道工厂启动一个匿名函数作为协程以生产通道
```go
func pump() chan int {
ch := make(chan int)
go func() {
for i := 0; ; i++ {
ch <- i
}
}()
return ch
}
```
5通道迭代器模板
6如何限制并发处理请求的数量参考[章节14.11](14.11.md)
7如何在多核CPU上实现并行计算参考[章节14.13](14.13.md)
8如何终止一个协程`runtime.Goexit()`
9简单的超时模板
```go
timeout := make(chan bool, 1)
go func() {
time.Sleep(1e9) // one second
timeout <- true
}()
select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out
}
```
10如何使用输入通道和输出通道代替锁
```go
func Worker(in, out chan *Task) {
for {
t := <-in
process(t)
out <- t
}
}
```
11如何在同步调用运行时间过长时将之丢弃参考[章节14.5](14.5.md) 第二个变体
12如何在通道中使用计时器和定时器参考[章节14.5](14.5.md)
13典型的服务器后端模型参考[章节14.4](14.4.md)
## 链接
- [目录](directory.md)
- 上一节:[文件](18.7.md)
- 下一节:[网络和网页应用](18.9.md)

21
eBook/18.9.md Normal file
View File

@@ -0,0 +1,21 @@
# 18.9 网络和网页应用
## 18.9.1 模板:
制作、解析并使模板生效:
```go
var strTempl = template.Must(template.New("TName").Parse(strTemplateHTML))
```
在网页应用中使用HTML过滤器过滤HTML特殊字符
`{{html .}}` 或者通过一个字段 `FieldName {{ .FieldName |html }}`
使用缓存模板(参考[章节15.7](15.7.md)
## 链接
- [目录](directory.md)
- 上一节:[协程goroutine与通道channel](18.8.md)
- 下一节:[其他](18.10.md)

View File

@@ -152,7 +152,7 @@
- 第16章常见的陷阱与错误
- 第17章模式
- 第18章出于性能考虑的实用代码片段
- 第18章[出于性能考虑的实用代码片段](18.0.md)
- 第19章构建一个完整的应用程序
- 第20章Go 语言在 Google App Engine 的使用
- 第21章实际部署案例