值得惯用的编程吗?一个ES6的例子 [英] Is it worth idiomatic programming? An ES6 example

查看:85
本文介绍了值得惯用的编程吗?一个ES6的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编程是关于如何实现任何代码的决策。根据这些决定,代码将或多或少地具有可读性,高效性,复杂性等。一个常见的决定也是或多或少地习惯性,即使用特定语句或您的编程语言或范例。



作为概念验证,我在Javascript中开发了两个代码片段来分析性能。目标是以 tagA | tagB | tagC 的形式生成一个字符串,其中 tagX 的数量是随机的,后缀 A B C 是随机整数。此外, tagX 不能重复。



第一个实现更惯用,而第二个实现更传统。接下来是每个代码段:



惯用语:

  performance.mark( 'A'); 

let tags = new Set(Array.from({length:tagCount},()=> Math.floor(Math.random()* 10)));
tags = Array.from(tags).map(x =>`tag $ {x}`)。join('|');

performance.mark('B');

传统

  performance.mark( 'C'); 

let tagset = new Set();
让tagstr =;

for(let tag = 0; tag< tagCount; tag ++){
tagset.add(Math.floor(Math.random()* 10));
}

tagset.forEach((tag)=> {
tagstr + ='tag'+ tag +'|'
});

tagstr = tagstr.slice(0,-1);

performance.mark('D');

为了衡量我使用过的表现 Performance Timing API



结果有点令人沮丧,至少对我而言。请注意传统方式如何比其他方式更有效。

 惯用语:0.436535 
繁体:0.048177

我已多次重复实验,结果相似



惯用法看起来非常酷而且更短,但效率低且难以阅读。



您如何看待它?使用惯用编程而不是传统编程是否值得?是否有一般性答案,或者它是否完全依赖于每个案例?



代码可读性和复杂性怎么样?



已编辑 tagX 无法重复。



EDITED :仅供参考,我已将完整代码上传到Github: https://github.com/aecostas/benchmark-js-looping

解决方案

< blockquote>

惯用法看起来非常酷而且更短,但效率较低且难以阅读


如果熟悉该语言的人发现难以阅读,那就不是惯用语了。 (你可能会使用这个词的一个定义 - 使用许多成语 - 但这并不是人们在提到惯用代码时的意思,尽管 Array.from({length}例如,是一个 idiom ¹,用于根据JavaScript中的函数填充数组。相反,它的代码是按照语言用户所期望的方式编写的。你可以通过命名一些东西来使它更接近:

  const tagNumbers = Array.from(
{length:tagCount },
()=> Math.floor(Math.random()* 10),
);

const uniqueTagNumbers = Array.from(new Set(tagNumbers));

const tagString =
uniqueTagNumbers
.map(n =>'tag'+ n)
.join('|');

并利用实践中存在的实用功能类型:

 从'...'导入生成; 
从'...'导入唯一;

const getRandomTag =()=>
Math.random()* 10 | 0;

const tags =
generate(tagCount,getRandomTag);

const tagString =
unique(tags)
.map(n =>'tag'+ n)
.join('|');

但是到目前为止你只能使用玩具示例。



至于绩效:并非所有事情都必须进行微观优化。这里你的两个例子具有相同的渐近时间和空间复杂度,这对于很多情况来说已经足够了。你正在用JavaScript编写,因为它的语言功能可以让你以性能为代价更好地表达自己。当它确实进行优化时,您可能希望编写更准确的基准测试(这在Node中非常难!) - 例如尝试重新排序这些测量结果。



¹,意思是表达语言的用户意识到的意思是没有表达本身传达的东西。

²或者因为其他人或其他一些人认为现在你被困在他们的代码上,或者可能是出于某种原因而不是表达本身,或者前面提到的人都在同一条船上,......

³哦,他是一个习语


Programming is about making decisions about how to implement any piece of code. Depending of such decisions, the code will be more or less readable, efficient, complex, etc. A common decision is also about to do it more or less idiomatic, that is, using specific statements or your programming language or paradigm.

As a proof of concept I have developed two code snippets, in Javascript, to analyze the performance. The goal is to generate a string in the form tagA|tagB|tagC where then number of tagX is random and the suffixes A, B, C are random integers. Moreover, tagX can not be repeated.

First implementation is more idiomatic, whereas the second one is more traditional. Next the code snippets of each one:

Idiomatic:

performance.mark('A');

let tags = new Set(Array.from({length: tagCount}, () => Math.floor(Math.random() * 10)));
tags = Array.from(tags).map(x => `tag${x}`).join('|');

performance.mark('B');

Traditional

performance.mark('C');

let tagset = new Set();
let tagstr = "";

for (let tag=0; tag<tagCount; tag++) {
    tagset.add(Math.floor(Math.random() * 10));
}

tagset.forEach((tag) => {
    tagstr += 'tag' + tag + '|'
});

tagstr = tagstr.slice(0, -1);

performance.mark('D');

To measure the performance I have used the Performance Timing API

The results are a bit surpraising, at least for me. Note how the traditional way is so much efficient than the other one.

Idiomatic: 0.436535
Traditional: 0.048177

I have repeated the experiment several times with similar results

Idiomatic way looks pretty cool and shorter, but it is less efficient and hard to read.

What do you think about it? Does it worth using idiomatic programming instead of traditional? Is there a general answer or it is strongly dependent of each case?

What about code readability and complexity?

EDITED: tagX can not be repeated.

EDITED: just for reference, I have uploaded the complete code to Github: https://github.com/aecostas/benchmark-js-looping

解决方案

Idiomatic way looks pretty cool and shorter, but it is less efficient and hard to read.

If people familiar with the language find it hard to read, it’s not "idiomatic". (You might be going by one definition of the word – "using many idiom¹s" – but this isn’t what people mean when they refer to idiomatic code, though it’s true that Array.from({length}, fn), for example, is an idiom¹ for filling an array based on a function in JavaScript. Rather, it’s code that’s written the way users of the language expect.) You could get it closer by naming some stuff:

const tagNumbers = Array.from(
    {length: tagCount},
    () => Math.floor(Math.random() * 10),
);

const uniqueTagNumbers = Array.from(new Set(tagNumbers));

const tagString =
    uniqueTagNumbers
        .map(n => 'tag' + n)
        .join('|');

and by making use of the type of utility functions that would exist in practice:

import generate from '…';
import unique from '…';

const getRandomTag = () =>
    Math.random() * 10 | 0;

const tags =
    generate(tagCount, getRandomTag);

const tagString =
    unique(tags)
        .map(n => 'tag' + n)
        .join('|');

There’s only so far you can go with toy examples, though.

As for performance: not everything has to be micro-optimized. Your two examples here have the same asymptotic time and space complexity, and that’s enough for many cases. You’re writing in JavaScript because its language features let you express yourself better² at the cost of performance, after all. And when it does come to optimization, you’ll probably want to write more accurate benchmarks (which is pretty hard in Node!) – e.g. try reordering those measurements.

¹ in the sense of being an expression that users of the language are aware means something without the expression itself conveying that clearly.
² or because someone else or some other group of people thought that and now you’re stuck working on their code, or maybe it was for some reason other than expressiveness per se, or the aforementioned people were in that same boat³, …
³ oh hey an idiom

这篇关于值得惯用的编程吗?一个ES6的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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