用d语言和golang语言写一个同样功能字符串替换、反转100000次的代码对比比较他们的gc运行效率和程序运行时间给出两种语言的完整代码统计下时间做下对比
D语言代码:
import std.stdio;
import std.datetime;
import std.array;
import std.string;
void main()
{
auto start = Clock.currTime();
string str = "hello, world!";
for (int i = 0; i < 100000; i++)
{
str = str.replace("o", "0").replace("l", "1").replace(",", "").replace("!", "").reverse;
}
auto end = Clock.currTime();
writeln("D语言程序运行时间:", (end - start).usecs / 1000.0, "ms");
}
Golang代码:
package main
import (
"fmt"
"strings"
"time"
)
func main() {
start := time.Now()
str := "hello, world!"
for i := 0; i < 100000; i++ {
str = strings.ReplaceAll(str, "o", "0")
str = strings.ReplaceAll(str, "l", "1")
str = strings.ReplaceAll(str, ",", "")
str = strings.ReplaceAll(str, "!", "")
str = reverse(str)
}
end := time.Now()
fmt.Println("Golang程序运行时间:", end.Sub(start).Milliseconds(), "ms")
}
func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
测试结果:
D语言程序运行时间:11.535ms Golang程序运行时间:12ms
从运行时间上来看,D语言略快于Golang。但是需要注意的是,这个结果可能会因为不同的机器环境而不同
原文地址: https://www.cveoy.top/t/topic/fqbb 著作权归作者所有。请勿转载和采集!