为什么的String.Format的重载存在吗? [英] Why do the overloads of String.Format exist?

查看:108
本文介绍了为什么的String.Format的重载存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用反射来看看的String.Format的实施,并一直在IM pression认为的String.Format的重载用了1,2及3个参数进行了优化,它接受一个对象数组的方法的版本。然而,我发现的是,他们在内部创建一个对象数组,然后调用一个方法,它接受一个对象数组。

I was using Reflector to look at the implementation of String.Format and had always been under the impression that the overloads of String.Format that took 1, 2 & 3 arguments were optimized versions of the method that takes an object array. However, what I found was that internally they create an object array and then call a method that takes an object array.

1 ARG

public static string Format(string format, object arg0)
{
    if (format == null)
    {
        throw new ArgumentNullException("format");
    }
    return Format(null, format, new object[] { arg0 });
}

2的args

public static string Format(string format, object arg0, object arg1)
{
    if (format == null)
    {
        throw new ArgumentNullException("format");
    }
    return Format(null, format, new object[] { arg0, arg1 });
}

3的args

public static string Format(string format, object arg0, object arg1, object arg2)
{
    if (format == null)
    {
        throw new ArgumentNullException("format");
    }
    return Format(null, format, new object[] { arg0, arg1, arg2 });
}

对象数组

public static string Format(string format, params object[] args)
{
    if ((format == null) || (args == null))
    {
        throw new ArgumentNullException((format == null) ? "format" : "args");
    }
    return Format(null, format, args);
}

在内部都最终会使用相同的code等使用1,2及3参数版本已快于对象数组版本。

Internally they all end up using the same code and so using the 1, 2 & 3 argument versions are no faster than the object array version.

所以我的问题是 - ?为什么他们存在

So my question is - why do they exist?

当您使用对象数组版本逗号分隔值列表,编译器会自动的参数转换成因为/ ParamArray关键字的PARAMS对象数组基本上是什么1,2及3版本做,所以他们似乎是多余的。为什么BCL设计师添加这些重载?

When you use the object array version with a comma separated list of values, the compiler automatically converts the arguments into an object array because of the params/ParamArray keyword which is essentially what the 1, 2 & 3 versions do, so they seem redundant. Why did the BCL designers add these overloads?

推荐答案

一个原因,因为汉斯提到,就是创建一个数组是很多不必要的开销在格式化字符串最常见的情况。这在EXE节省了空间。

One reason, as Hans mentions, is that creating an array is a lot of unnecessary overhead in most common cases of formatting a string. This saves space in the EXE.

另一个原因是,不是所有的语言都支持可变参数的函数(在C#中使用 PARAMS )。这使得这些语言的用户,以避免阵列创建的字符串格式化的最常见的情况。这可以节省大量的没有数组创建和初始化简单的语法语言。

Another reason is that not all languages support variadic functions (use of params in C#). This allows users of those languages to avoid array creation for the most common cases of string formatting. This saves a lot for languages that don't have simple syntax for array creation and initialization.

这篇关于为什么的String.Format的重载存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆