您的位置:首页 > 其它

使用ToUpperInvariant避免使用ToUpper

2011-07-15 09:41 169 查看
ToUpperInvariant使用不依赖于区域性进行转换,而ToUpper则使用了当前线程的CultureInfo,进行转换,所以性能会有所影响,以下为测试:
[Test]
        public void TestInvariant()
        {
            Int32 count = 1000 * 1000;
            Stopwatch watch = new Stopwatch();

            String str = "abcdefghijklmnopqrstuvwxyz中华人民共和国";
            watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
            {
                str.ToUpperInvariant();
            }
            Console.WriteLine("ToUpperInvariant:{0}", watch.Elapsed.ToString());
        }

        [Test]
        public void TestNoInvariant()
        {
            Int32 count = 1000 * 1000;
            Stopwatch watch = new Stopwatch();

            String str = "abcdefghijklmnopqrstuvwxyz中华人民共和国";
            watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
            {
                str.ToUpper();
            }
            Console.WriteLine("ToUpper:{0}", watch.Elapsed.ToString());
        }

结果:
ToUpperInvariant:00:00:00.2980660
ToUpper:00:00:00.3281423
如果 确认当前的比较和区域性无关的话,推荐使用ToUppperInvariant
ToUpperInvariant
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: