跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Go 编程语言] 关于 Go 递归性能的疑问

发表于

OP 是 Go 语言初学者,学到递归这里实现斐波那契数列的计算,看到的资料都说 Go 没有对尾递归做优化,但是我用尾递归的方式测试之后,发现性能会比最原始的递归方式强非常多,这是什么原因呢?

package main

import (
	"fmt"
	"time"
)

func fibonacciTailRecursive(n int, a int, b int) int {
	if n == 0 {
		return a
	}
	return fibonacciTailRecursive(n-1, b, a+b)
}

func fib(n int) int {
	if n <= 1 {
		return n
	}
	return fib(n-1) + fib(n-2)
}
func fib1(n int) int {
	return fibonacciTailRecursive(n, 0, 1)
}

func main() {
	n := 40
	start := time.Now()
	result := fib(n)
	duration := time.Since(start)
	fmt.Println(result, duration) // 常规的递归结果 102334155 394.601829ms

	start = time.Now()
	result = fib1(n)
	duration = time.Since(start)
	fmt.Println(result, duration) // 使用尾递归结果 102334155 90ns
}

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.