我是 C# 新手,一直在玩它。我在 C# 中實作了冒泡排序,希望它比 JavaScript 更快,因為它是一種編譯語言,但我的速度要慢得多。
我正在對 100,000 個數字進行排序。
在 C# 中,我的速度大約為:1 分 30 秒
C#代碼:
using System.Diagnostics;
public class Program {
public static void Main(string[] args) {
List<int> randoms = generateRandoms(0, 1000000, 100000);
Console.WriteLine(randoms.Count);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
bubbleSort(randoms);
stopWatch.Stop();
TimeSpan timeSpan = stopWatch.Elapsed;
Console.WriteLine("Total processing time... {0:00}:{1:00}:{2:00}.{3:000}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
Console.Read();
}
static List<int> generateRandoms(int min, int max, int amount) {
Random rnd = new Random();
List<int> randoms = new List<int>();
for (int i = 0; i < amount; i ) {
int r = rnd.Next(min, max 1);
randoms.Add(r);
}
return randoms;
}
static List<int> bubbleSort(List<int> list) {
//Bubble sort
for (int i = 0; i < list.Count; i ) {
for (int j = 0; j < list.Count - i - 1; j ) {
if (list[j] > list[j 1]) {
int temp = list[j];
list[j] = list[j 1];
list[j 1] = temp;
}
}
}
return list;
}
static void print(List<int> list) {
for (int i = 0; i < list.Count; i ) {
Console.WriteLine(list[i]);
}
}
}
在 JavaScript 中,我得到大約:30 秒
JavaScript 代碼:
function bubbleSort(array) {
for (let i = 0; i < array.length; i ) {
for (let j = 0; j < array.length-i-1; j ) {
if (array[j] > array[j 1]) {
[array[j], array[j 1]] = [array[j 1], array[j]];
}
}
}
}
function generateRandoms(min, max, n) {
const arr = [];
for (let i = 0; i < n; i ) {
arr.push(Math.floor(Math.random() * (max-min 1) min));
}
return arr;
}
const array = generateRandoms(0, 1000000, 100000);
console.log(array.length);
const start = new Date();
bubbleSort(array);
const end = new Date();
console.log(`Performance: ${end - start}ms`);
我認為它與 C# 中的“List”資料結構有關,但在查看檔案后,我在 bubbleSort 函式中使用的所有操作似乎都是 O(1)
有誰知道為什么 C# 的速度對我來說要差得多?我正在使用.Net v6.0.201。我也在為這兩個程式使用 VSCode。
uj5u.com熱心網友回復:
在發布模式下構建時,C# 與 JS 一樣快,甚至快一點。至少在我的電腦上。
Total processing time... 00:01:00.611: 除錯箱
Total processing time... 00:00:19.586: 釋放箱
uj5u.com熱心網友回復:
我認為它與 C# 中的“List”資料結構有關,但在查看檔案后,我在 bubbleSort 函式中使用的所有操作似乎都是 O(1)
O(1) 不一定很快,它只是恒定的。將 C# 代碼更改為使用陣列可以使其速度大致翻倍。不確定為什么會這樣(List 在后臺使用陣列),但 IIRC 陣列有時能夠省略邊界檢查。
此外,您的 C# 交換比您的 JS 交換做的作業更多;你可以替換這個:
int temp = list[j];
list[j] = list[j 1];
list[j 1] = temp;
有了這個:
(list[j], list[j 1]) = (list[j 1], list[j]);
在這些變化之后,這兩種語言更接近了,但 JS 仍然獲勝;我不確定為什么。
更新:如果我記得在發布模式下編譯,C# 對我來說更快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443135.html
標籤:javascript C# 排序 冒泡排序
上一篇:字串中的特定字符數
