form1.cs

来自「Microsoft Mobile Development Handbook的代码」· CS 代码 · 共 128 行

CS
128
字号
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace CodeForChapter5cs
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    // string vs stringbuilder
    private void menuItem1_Click(object sender, EventArgs e)
    {
      GC.Collect();
      Stopwatch sw = Stopwatch.StartNew();
      PerfTests.UseString();
      sw.Stop();

      long mils1 = sw.ElapsedMilliseconds;
      sw.Reset();
      sw.Start();
      PerfTests.UseStringBuilder();
      sw.Stop();
      long mils2 = sw.ElapsedMilliseconds;

      MessageBox.Show(mils1.ToString() + " > " + mils2.ToString());
    }

    #region measuring with tickcount and stopwatch
    private void SomeMethodA()
    {
      Stopwatch sw = new Stopwatch();
      sw.Start();

      // some long running task
      Thread.Sleep(2000);

      sw.Stop();

      long millis = sw.ElapsedMilliseconds;

      MessageBox.Show(millis.ToString());
    }

    private void SomeMethodB()
    {
      int start = Environment.TickCount;

      // some long running task
      Thread.Sleep(2000);

      int end = Environment.TickCount;

      int millis = end - start;

      MessageBox.Show(millis.ToString());
    }

    private void menuItem4_Click(object sender, EventArgs e)
    {
      this.SomeMethodB();
    }

    private void menuItem3_Click(object sender, EventArgs e)
    {
      this.SomeMethodA();
    } 
    #endregion

    // collections
    private void button1_Click(object sender, EventArgs e)
    {
      GC.Collect();
      Stopwatch sw = Stopwatch.StartNew();
      PerfTests.UseArray();
      sw.Stop();
      long mils1 = sw.ElapsedMilliseconds;

      sw.Reset();
      GC.Collect();
      sw.Start();
      PerfTests.UseGenerics();
      sw.Stop();
      long mils2 = sw.ElapsedMilliseconds;

      sw.Reset();
      GC.Collect();
      sw.Start();
      PerfTests.UseArrayList();
      sw.Stop();
      long mils3 = sw.ElapsedMilliseconds;

      MessageBox.Show(mils1.ToString() + " > " + mils2.ToString()
        + " > " + mils3.ToString());
    }

    // memory
    private void button2_Click(object sender, EventArgs e)
    {
      Memory.ShowMemory();
    }

    // virtual calls
    private void button3_Click(object sender, EventArgs e)
    {
      MyClass mc = new MyClass();
      mc.Test2();
      mc.Test1();
    }

    private void button4_Click(object sender, EventArgs e)
    {
      GC.Collect();
      GC.WaitForPendingFinalizers();
    }

  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?