字符串字面性能VS会话[...]字典键常量 [英] Performance of String literals vs constants for Session[...] dictionary keys

查看:92
本文介绍了字符串字面性能VS会话[...]字典键常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检索用户特定的数据,如计算机[CartItems] =会话[CartItems]; 用于字符串为每个请求键。我应该使用常量呢?

I'm retrieving user-specific data like ViewData["CartItems"] = Session["CartItems"]; with a string literal for keys on every request. Should I be using constants for this?

如果有,我应该如何去实现常用的字符串,并将其显著影响到一个高流量的网站性能?

If yes, how should I go about implementing frequently used string literals and will it significantly affect performance on a high-traffic site?

<一个href=\"http://stackoverflow.com/questions/1166254/should-i-use-string-constants-or-string-literals\">Related问题不涉及ASP.NET MVC或会话

Related question does not address ASP.NET MVC or Session.

推荐答案

要使用常量的原因是可维护性,而不是性能做。性能是差不多的两种方式。

The reason to use constants has to do with maintainability, not performance. Performance is about the same either way.

通过字符串文字,你永远无法知道它是否是另一个相同字符串有意还是巧合,所以当它的时间来改变一个,你不知道哪个其他的改变。但如果你有常量的值,你只是做在一个地方的变化。

With a string literal, you can never tell whether it's the same as another string literal intentionally or by coincidence, so when it's time to change one, you don't know which other ones to change. But if you have the values in constants, you just make the change in one place.

错误:

ViewData["username"] = Session["username"];

const UserNameSessionKey = "username";
const UserNameViewDataKey = "username";

ViewData[UserNameViewDataKey] = Session[UserNameSessionkey];

现在想象没有想改变它的任何可视数据密钥变更会话密钥username的值...

Now imagine changing the value of the session key to "userName" without wanting to change it for any viewdata key...

这篇关于字符串字面性能VS会话[...]字典键常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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