字符串操作性能优化

baiyujing 2018-02-24 原文

字符串操作性能优化

  昨天看到关于字符串操作性能优化的帖子。

  1.使用值类型的ToString方法

  首先理解装箱和拆箱:1.装箱在值类型向引用类型转换时发生。2. 拆箱在引用类型向值类型转换时发生装箱操作和拆箱操作是要额外耗费cpu和内存资源的,所以在c# 2.0之后引入了泛型来减少装箱操作和拆箱操作消耗

  值类型ToString是不会装箱。例如:string a = a + 1;和string a= a + 1.tostring();前者会引起装箱额外消耗资源。

  2.运用StringBuilder类 

  String是不可变的。 对象是不可变的。 每次使用 System.String 类中的一个方法时,都要在内存中创建一个新的字符串对象,这就需要为该新对象分配新的空间。 在需要对字符串执行重复修改的情况下,与创建新的 String 对象相关的系统开销可能会非常大。 如果要修改字符串而不创建新的对象,则可以使用System.Text.StringBuilder 类。 例如,当在一个循环中将许多字符串连接在一起时,使用 StringBuilder 类可以提升性能。

  下面简单写个案例实践一下:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// str + i引起装箱消耗额外资源
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public string Test1(int count)
        {
            Stopwatch watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
            {
                string a = "a";
                a = a + 1;
            }
            watch.Stop();
            float sec = watch.ElapsedMilliseconds / 1000.0f;
            return string.Format("耗时:{0}秒", sec);
        }
        /// <summary>
        /// 值类型ToString不会装箱
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public string Test2(int count)
        {
            Stopwatch watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
            {
                string a = "a";
                a = a + 1.ToString();
            }
            watch.Stop();
            float sec = watch.ElapsedMilliseconds / 1000.0f;
            return string.Format("耗时:{0}秒", sec);
        }
        /// <summary>
        /// str + i引起装箱消耗额外资源
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public string Test3(int count)
        {
            string str = "";
            Stopwatch watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
            {
                str = str + i;
            }
            watch.Stop();
            float sec = watch.ElapsedMilliseconds / 1000.0f;
            return string.Format("耗时:{0}秒", sec);
        }
        /// <summary>
        /// 使用String,在内存中创建一个新的字符串对象
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public string Test4(int count)
        {
            string str = "";
            Stopwatch watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
            {
                str = str + i.ToString();
            }
            watch.Stop();
            float sec = watch.ElapsedMilliseconds / 1000.0f;
            return string.Format("耗时:{0}秒", sec);
        }
        /// <summary>
        /// 使用StringBuilder
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public string Test5(int count)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            Stopwatch watch = Stopwatch.StartNew();
            for (int i = 0; i < count; i++)
            {
                str.Append(i.ToString());
            }
            string result = str.ToString();
            watch.Stop();
            float sec = watch.ElapsedMilliseconds / 1000.0f;
            return string.Format("耗时:{0}秒", sec);
        }
    }

  多次运行结果可以看到Test1,Test2每次装箱引起性能消耗不是很大,当到100000000(一亿)时有一秒左右差距。Test4,Test5当运行10000时,差距零点几,当运行100000时使用StringBuilder明显性能提升,当然我们可能也用不到如此长的string字符串,以前有个项目sql语句非常复杂是通过StringBuilder拼接的,当时只知道照着用,现在才知道还可以略微提升性能。

发表于 2018-02-24 15:25 阅读() 评论() 编辑 收藏

 

版权声明:本文为baiyujing原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/baiyujing/p/8465996.html

字符串操作性能优化的更多相关文章

  1. Spring IoC 容器和 bean 对象

    程序的耦合性: 耦合性(Coupling),又叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的 […]...

  2. eclipse安装自定义折叠插件之后导致 String index out of range: xx 使java文件不能打开

    安装了 com.cb.eclipse.folding折叠插件, 在代码比较特殊或代码比较多的情况下,java文 […]...

  3. 400错误,Required String parameter \’paramter\’ is not present

    1.就拿简单的登录来说吧,这是开始的代码   @RequestMapping(value=”/lo […]...

  4. Java StringBuffer 和 StringBuilder 类

    当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。 和 Str […]...

  5. 深入理解JS中的对象(二):new 的工作原理

    目录 序言 不同返回值的构造函数 深入 new 调用函数原理 总结 参考 1.序言 在 深入理解JS中的对象( […]...

  6. Java实体类对象与Map对象互转

    实体类对象转Map对象使用Fastjsonpublic Map toMapByJson(T obj) {// 默认序列化为数字类型的时间戳// String jsonStr = JSON.toJ...

  7. [Javascript] String in Javascript

    String in Javascript is immutable. Means that once they were created, they cannot be modified.This also means that sim...

  8. Java String indexOf()方法

    1 public class Test { 2 public static void main(String[ […]...

随机推荐

  1. 关于数据库,程序员应该了解的那些事

    数据库的选型 对于很多程序员来说,公司选择什么样的数据库,基本不需要你来决定。当你加入一个公司的时候,公司的大 […]...

  2. Hibernate的HQL查询 – jadmin

    Hibernate的HQL查询 4.3 使用HQL查询 Hibernate提供了异常强大的查询体系,使用Hib […]...

  3. 【转载】分布式RPC框架性能大比拼

    dubbo、motan、rpcx、gRPC、thrift的性能比较 Dubbo 是阿里巴巴公司开源的一个Jav […]...

  4. Git 如何优雅地回退代码

    前言 从接触编程就开始使用 Git 进行代码管理,先是自己玩 Github,又在工作中使用 Gitlab,虽然 […]...

  5. jQuery系列 第三章 jQuery框架操作CSS

    jQuery系列 第三章 jQuery框架操作CSS 第三章 jQuery框架操作CSS 3.1 jQuery […]...

  6. W5500嵌入式开发

    W5500是韩国一款集成全硬件 TCP/IP 协议栈的嵌入式以太网控制器,W5500同时也是一颗工业级以太网控 […]...

  7. Java 读取Word文本/段落格式属性

    本文介绍通过Java后端程序代码来读取Word文本和段落格式的方法。 本次测试环境如下: Word版本:201 […]...

  8. 腾讯海量数据处理平台TDW – 白乔

    腾讯海量数据处理平台TDW TDW是腾讯海量数据处理平台中最核心的模块,它有以下几个作用: 提供海量的离线计算 […]...

展开目录

目录导航